
   function addLoadEvent(i_func) {
  if (typeof i_func == 'function') {
    if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', i_func, false);
    }
    else if (window.attachEvent) {
      window.attachEvent('onload', i_func);
    }
    else if (typeof window.onload == 'function') {
      var old_func = window.onload;
      window.onload = function () {
        old_func(); i_func();
      }
    }
    else {
      window.onload = i_func;
    }
  }
}

function addEvent(obj, event, func, useCapture) {
  if (obj.addEventListener) {
    obj.addEventListener(event, func, typeof useCapture == 'undefined' ? false : useCapture);
  }
  else if (obj.attachEvent) {
    obj.attachEvent('on' + event, func);
  }
  else {
    obj['on' + event] = func;
    }
}

function setAttribute(obj, key, value) {
	if (obj.setAttribute) {
		obj.setAttribute(key, value);
	}
	else {
		obj[key] = value;
	}
}

function getAttribute(obj, key) {
	var res = '';
	if (obj.getAttribute) {
		res = obj.getAttribute(key);
	}
	else {
		res = obj[key];
	}	
	
	return res;
}

function SendAnalyticsEvent(i_category, i_action, i_label, i_value) {
  var category = typeof i_category == 'string' ? i_category : '';
  var action = typeof i_action== 'string' ? i_action: '';
  var label = typeof i_label== 'string' ? i_label: '';
  var value = typeof i_value== 'string' ? i_value: '';

  pageTracker._trackEvent(category, action, label, value);
}

/*Send Unica wrapper function */
function SendUnicaCode(msg)
{
    try 
    {
        ntptEventTag("ev=" + msg);
    } catch (err) { }
}

/* Add new sCut parameter */

function AddsCutParam(paramName, value)
{
   sCut= sCut+ paramName + "=" + value + "&";
}

/* Check that browser is IE */
function IsIEBrowser() 
{
    if (navigator.appVersion.indexOf("IE") > 0) 
    {
        return true;
    }
    return false;
}
function IsIE8Browser() 
{
    if (navigator.appVersion.indexOf("IE 8") > 0) 
    {
        return true;
    }
    return false;
}
function IsFFBrowser() 
{
     if (navigator.indexOf("Firefox") > 0)
    {
        return true;
    }
    return false;
}

/*Set background image in specified control*/
function setBGImage(control, bgImagePath) {
    if (control != null) {
        control.style.backgroundImage = "url('" + bgImagePath + "')";
    }
}

/* Toggles element display */
function toggleElement(id) {
        elem = document.getElementById(id);
        elem.style.display= (elem.style.display=="none") ? "block":"none";
}

/* Position xpos, ypos of background image */
function positionBackground(control,xpos,ypos) {
       control.style.backgroundPosition=xpos+"px "+ypos+"px";
}

/* Fetches query string value */
function fetchParameterValue(param) {
    query_str = window.location.search.substring(1);
    pairs = query_str.split("&");
    for (i=0; i<pairs.length; i++) {
        kv = pairs[i].split("=");
        if (kv[0] == param) { 
            return kv[1];
        }
    }
    return "Undefined";
}

function isEmpty(obj) {
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      return false;
    }
  }

  return true;
}

   function initializeEyeView()
{
    if(ev_site_id != '')
    {
        window["EngagerTag"] = {};
        EngagerTag.start = function() { }
        EngagerTag.end = function() { }
        document.write(unescape("%3Csc" + "ript src='" + location.protocol + "//serve.eyeviewdigital.com/engager.php?sid=" + ev_site_id + "' type='text/javascript'%3E%3C/sc" + "ript%3E"));
        ev_site_id = '';
	}
}

   var MM_contentVersion = 6;
var MM_FlashCanPlay;

var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i)
	    {
		if (isNaN(parseInt(words[i])))
		continue;
		var MM_PluginVersion = words[i]; 
	    }
	MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
   && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}

function showFlash(flashPath,flashWidth, flashHeight)
{
        document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + flashWidth + '" height="' + flashHeight + '" id="flash_id" align="middle" VIEWASTEXT>');
        document.write('<param name="movie" value="' + flashPath + '" />');
        document.write('<param name="quality" value="high" />');
        document.write('<param name="bgcolor" value="#000000" />');
        document.write('<param name="wmode" VALUE="transparent" />');
        document.write('<param name="allowScriptAccess" value="always" />');
        document.write('<embed src="'+ flashPath + '"  wmode="transparent" quality="high" bgcolor="#000000" width="' + flashWidth + '" height="' + flashHeight + '" name="flash_id" allowScriptAccess="always" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
        document.write('</object>');
}

   function OpenAndDownload(i_location, i_brand) {
  var location = typeof i_location == 'undefined' ? 0 : parseInt(i_location);
  location = (isNaN(location) || location <= 0 ? '0000' : location.toString());
  var brand = typeof i_brand == 'undefined' ? '888casino' : i_brand;
  
  //unica
  try {
    ntptAddPair("dl", location);
    SendUnicaCode('download_' + brand);
  } catch(err) {}
  
  // if download process already started -> doesn't show exit popup in future
  showExitPopup = false;
  setDownloadStatus();

  var sURLreg = "/downloadclient.htm?dl=" + location + "&DownloadBrand=" + brand;
  
  if ('conversion' in window) {
    if (conversion.is_running) {
      conversion.reportConversionGoal(brand);
    }
    sURLreg += conversion.getSt() + conversion.getMkw();
  }
  
  sURLreg += '&' + sCut + getDlp();
   
  var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  if (is_chrome) {
    window.location.href = sURLreg;
  }
  else {
    window.open(sURLreg, "popDown", "width=620,height=150,top=0,left=0");
  }
}

function OpenLiveCasino(i_location) {
  var location = typeof i_location == 'undefined' ? 0 : parseInt(i_location);
  location = (isNaN(location) || location <= 0 ? '4679' : location.toString());

  try {
    ntptAddPair("dl", location);
    SendUnicaCode('nodownload_livecasino');
  } catch(err){}
  
  var filename =  "http://ndl.888.com/casino/application/ViewActual.html?mode=3&LangID=da&dl=" + location + "&skin=5&brand=0";
  
  if ('conversion' in window) {
    if (conversion.is_running) {
      conversion.reportConversionGoal('livecasino');
    }
    filename += conversion.getSt() + conversion.getMkw();
  }

  filename += '&' + sCut + getDlp();
 
  var w = 801;
  var h = 571;
  var l = (window.screen.width-w)/2;
  var t = (window.screen.height-h)/2;

  var opened = window.open(filename, "Offline", "resizable=no,status=no,scrollbars=no,toolbar=no,menubar=no,left=" + l + ",top=" + t + ",width=" + w + ",height=" + h);
}

function NoDownloadPoker(i_location, i_bannerID) {
  var location = typeof i_location == 'undefined' ? 0 : parseInt(i_location);
  location = (isNaN(location) || location <= 0 ? '0000' : location.toString());
  var banner = typeof i_bannerID == 'undefined' ? null : getBanner(i_bannerID);
  
  try {
    ntptAddPair("dl", location);
    SendUnicaCode('nodownload_888poker');
  } catch(err){}
  
  //if NOT from landing page (out of the frame)
  if (window.name != "") {
    setDownloadStatus();
  }

  var filename = "http://ndl.888.com/poker/flashpoker_real/application/RLFlashPoker.html?dl=" + location + "&skin=4&brand=1&langid=da&";
  
  if ('conversion' in window) {
    if (conversion.is_running) {
      conversion.reportConversionGoal('poker-ndl');
    }
    filename += conversion.getSt() + conversion.getMkw();
  }
  
  filename += '&' + sCut + getDlp();
  
  var w = 820;
  var h = 565;
  var l = (window.screen.width-w)/2;
  var t = (window.screen.height-h)/2; 
      
  var opened = window.open(filename, null, "height=" + h + ",width=" + w + ",status=no,toolbar=no,menubar=no,location=no,resize=no,left="+l+",top="+t);
  
  if (!opened && banner != null) {
    banner.openWindow(filename, null, "height=" + h + ",width=" + w + ",status=no,toolbar=no,menubar=no,location=no,resize=no,left="+l+",top="+t);
  }
}

function NoDownloadCasino(i_location, i_bannerID, i_force) {
  var location = typeof i_location == 'undefined' ? 0 : parseInt(i_location);
  location = (isNaN(location) || location <= 0 ? '0000' : location.toString());  
  var banner = typeof i_bannerID == 'undefined' ? null : getBanner(i_bannerID);

  var force = typeof i_force != 'undefined' && i_force;
  
  // overlay patch
  if ((rlCountry == 'dnk' || rlCountry == 'deu') && !isMac() && !force) {
    showNDLInfoOverlay(location);
    return false;
  }
  
  try {
    ntptAddPair("dl", location);
    SendUnicaCode('nodownload_888casino');
  } catch(err){}

  var skin = (typeof rlCountry == 'string' && rlCountry == 'gbr') ? '3' : '4';
  var filename =  "http://ndl.888.com/casino/application/ViewActual.html?dl=" + location + '&skin=' + skin + '&mode=2&brand=0&LangID=da';

  if ('conversion' in window) {
    if (conversion.is_running) {
      conversion.reportConversionGoal('casino-ndl');
    }
    filename += conversion.getSt() + conversion.getMkw();
  }
  
  filename += '&' + sCut + getDlp();

  var w = 801;
  var h = 571;
  var l = (window.screen.width-w)/2;
  var t = (window.screen.height-h)/2;
  
  var opened = window.open(filename, "Offline", "resizable=no,status=no,scrollbars=no,toolbar=no,menubar=no,left=" + l + ",top=" + t + ",width=" + w + ",height=" + h);

  if (!opened && banner != null) {
    banner.openWindow(filename ,"Offline","resizable=no,status=no,scrollbars=no,toolbar=no,menubar=no,left=" + l + ",top=" + t + ",width=" + w + ",height=" + h);
  }   
}

function getDlp() {
  var dlp = '';
  
  try {
    dlp = encodeURIComponent(document.location.href);
    dlp = dlp.replace(/\./gi, "%2E");
  }
  catch (err) { }
  
  return (dlp != '' ? ('&dlp=' + dlp) : '');
}

function setDownloadStatus() {
  setCookie('downloaded', '1', '/');
}

function setCookie(name, value) {
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var path = (argc > 2) ? argv[2] : null;
    var expires = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;

    document.cookie = name + "=" + escape (value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain))
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) 
    return null;
  }
  else {
    begin += 2;
  }
  
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) {
      end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}

function openDL() {
  OpenAndDownload('6246', '888casino')
}

function showNDLInfoOverlay(i_location) {
  var ie = isIE();

  var wrapper_element = document.createElement('div');
  setAttribute(wrapper_element, 'id', 'ndl_info_wrapper');
  wrapper_element.style.position = ie ? 'absolute' : 'fixed';
  wrapper_element.style.top = wrapper_element.style.right = wrapper_element.style.bottom = wrapper_element.style.left =  '0px';
  if (ie) {
    wrapper_element.style.width = '100%';
    wrapper_element.style.height = '100%';
  }
  
  // Create overlay (black screen)
  var overlay_element = document.createElement('div');
  overlay_element.innerHTML = '&nbsp;';
  overlay_element.style.position = ie ? 'absolute' : 'fixed';
  overlay_element.style.top = overlay_element.style.right = overlay_element.style.bottom = overlay_element.style.left = '0px';
  overlay_element.style.background = 'black';
  if (ie) {
    overlay_element.style.width = '100%';
    overlay_element.style.filter="alpha(opacity = '70')";
  }
  else {
    overlay_element.style.opacity = 0.7;
  }
  wrapper_element.appendChild(overlay_element);
  
  // create map
  var map_element = document.createElement('map');
  setAttribute(map_element, 'name',  'ndl_info_map');
  setAttribute(map_element, 'id',  'ndl_info_map');

  // Download area
  var area_element = document.createElement('area');
  setAttribute(area_element, 'shape', 'rect');
  setAttribute(area_element, 'coords', '335,192,615,253');
  setAttribute(area_element, 'href', 'javascript:void();');
  addEvent(area_element, 'click', function () {
    OpenAndDownload(i_location, '888casino');
    hideNDLInfoOverlay();
    return false;
  });
  map_element.appendChild(area_element);

  // No-Download area
  var area_element = document.createElement('area');
  setAttribute(area_element, 'shape', 'rect');
  setAttribute(area_element, 'coords', '352,281,595,316');
  setAttribute(area_element, 'href', 'javascript:void();');
  addEvent(area_element, 'click', function () {
    NoDownloadCasino(i_location, undefined, true);
    hideNDLInfoOverlay();
    return false;
  });
  map_element.appendChild(area_element);

  // close area
  var area_element = document.createElement('area');
  setAttribute(area_element, 'shape', 'rect');
  setAttribute(area_element, 'coords', '655,8,683,39');
  setAttribute(area_element, 'href', 'javascript:void();');
  addEvent(area_element, 'click', hideNDLInfoOverlay);
  map_element.appendChild(area_element);
  
  wrapper_element.appendChild(map_element);
  
  // Create popup element
  var popup_element = document.createElement('div');
  popup_element.style.left = '50%';
  popup_element.style.marginLeft = '-345px';
  popup_element.style.position = ie ? 'absolute' : 'fixed';
  popup_element.style.zIndex = '10';
  
   // Create image inside the popup
  var images_by_country_and_lang = {
    'dnk' : {
      'en' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-en_tcm309-57003.jpg',
      'da' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-da_tcm309-57033.jpg',
      'de' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-en_tcm309-57003.jpg',
      'es' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-en_tcm309-57003.jpg',
      'other' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-en_tcm309-57003.jpg'
    },
    'deu' : {
      'en' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-germany-en_tcm309-57121.jpg',
      'de' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-germany-de_tcm309-57122.jpg',
      'da' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-germany-en_tcm309-57121.jpg',
      'es' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-germany-en_tcm309-57121.jpg',
      'other' : 'http://images.images4us.com/888/da/NDL-free-spin-popup-patch-germany-en_tcm309-57121.jpg'
    },
	'other' : {
	
	}
  };
  
  var img_element = document.createElement('img');
  var images_by_lang = rlCountry in images_by_country_and_lang ? images_by_country_and_lang[rlCountry] : images_by_country_and_lang['other'];
  var image_src = rlLang in images_by_lang ? images_by_lang[rlLang] : images_by_lang['other'];
  
  img_element.src = image_src;
  img_element.border = '0';
  img_element.useMap = '#ndl_info_map';
  
  var height = document.body.clientHeight;
  overlay_element.style.height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) + 'px';
  popup_element.style.top = ((Math.max(373 + 100, height) - 373) / 2) + 'px';

  popup_element.appendChild(img_element);
  
  wrapper_element.appendChild(popup_element);
    
  document.body.appendChild(wrapper_element);
  if (ie && 'scrollTo' in window) {
    window.scrollTo(0, 0);
  }
}

function hideNDLInfoOverlay() {
  var wrapper_element = document.getElementById('ndl_info_wrapper');
  if (wrapper_element != null) {
    document.body.removeChild(wrapper_element);
  }
}

   var showExitPopup = true;

var ExitPopup_Message = "";
var ExitPopup_OkUnica = "";
var ExitPopup_CancelUnica = "";
var ExitPopup_OkURL = "";
var ExitPopup_OkParameters = "";

function InitExitPopup(exitPopup_Message, exitPopup_OkUnica, exitPopup_CancelUnica, exitPopup_OkURL, exitPopup_OkParameters ){
	ExitPopup_Message = exitPopup_Message;
	ExitPopup_OkUnica = exitPopup_OkUnica;
	ExitPopup_CancelUnica = exitPopup_CancelUnica;
	ExitPopup_OkURL = exitPopup_OkURL;
	ExitPopup_OkParameters = exitPopup_OkParameters;
	RegisterExitPopup();
}

function RegisterExitPopup() {
  if (rlFlag.charAt(3) != '1') //If the 4th char in rlFlag is not 1, load function
  {
    try {
        if (!IsIEBrowser()) {
            var bodyTag = document.getElementsByTagName("BODY")[0];
            if (bodyTag != null) {
                bodyTag.setAttribute("onbeforeunload", "ConfirmExit(event);");
                bodyTag.setAttribute("onmousedown", "SetExitFlag(event);");
            }
        }
        else {
            attachEvent("onunload", ConfirmExit);
            document.attachEvent("onmousedown", SetExitFlag);
        }
    }
    catch (e) {
        /*alert(e.description);*/
    }
  }
}

function SetExitFlag(event) {
    var ref = "";
    var srcEl = event.srcElement || event.target;
    // do nothing if event source is undefined (clicking on scrollbars, etc.)
    if (srcEl == null) {
        return;
    }

    if (srcEl.id == "languageSelect") {
        showExitPopup = false;
        return;
    }
    // do not display exit popup when clicking language menu
    var currentNode = srcEl;
    while (currentNode.tagName != "BODY") {
        var currentParentNode = currentNode.parentNode;
        if (currentParentNode == null) {
            break;
        }
        else {
            currentNode = currentParentNode;
        }
    }

    //check if the element that was pressed was an anchor
    while ((srcEl != null) && (srcEl.tagName != "A") && (srcEl.tagName != "AREA") && (srcEl.tagName != "BODY"))
        srcEl = srcEl.parentElement || srcEl.parentNode;

    // do not display exit popup when clicking links
    if ((srcEl != null) && (srcEl.tagName == "A")) {
        showExitPopup = false;
    }
}

function ConfirmExit(event) {
    if (showExitPopup)
     {
            if (window.confirm(ExitPopup_Message)) {
            try {
                SendUnicaCode(ExitPopup_OkUnica);
            } catch (err) { /* do nothing if error */ }
            window.open(ExitPopup_OkURL, '', ExitPopup_OkParameters);
        } else {
            try {
                SendUnicaCode(ExitPopup_CancelUnica);
            } catch (err) { /* do nothing if error */ }
        }
    }
}


   /* Methods represent ExpandableDiv logic */

// Expands expandable div
// Parameters:
//  expTitleDiv - title div element
//  expTextDiv - rich text div element
function expandExpDiv(expTitleDiv, expTextDiv) {
    expTextDiv.style.display = 'block';
    var spans = expTitleDiv.getElementsByTagName('div');
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].className == 'plus') {
            spans[i].style.display = 'none';
        }
        else if (spans[i].className == 'minus') {
            spans[i].style.display = 'inline';
        }
    }
}

// Collapses expandable div
// Parameters:
//  expTitleDiv - title div element
//  expTextDiv - rich text div element
function collapseExpDiv(expTitleDiv, expTextDiv) {
    expTextDiv.style.display = 'none';
    var spans = expTitleDiv.getElementsByTagName('div');
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].className == 'plus') {
            spans[i].style.display = 'inline';
        }
        else if (spans[i].className == 'minus') {
            spans[i].style.display = 'none';
        }
    }
}

// Expands or collapses expandable div
// Parematers:
//  expDiv - div element, must contains title and rich text divs
function toggleExpDiv(expDiv) {
    if (expDiv) {
        var title = null;
        var text = null;
        var innerDivs = expDiv.getElementsByTagName('div');

        // get title and rich text divs
        for (var i = 0; i < innerDivs.length; i++) {
            if (innerDivs[i].className == 'expandableTitle') {
                title = innerDivs[i];
            }
            else if (innerDivs[i].className == 'expandableRichText Closed') {
                text = innerDivs[i];
            }
        }

        if (title && text) {
            if (text.style.display == 'none' || text.style.display == '') {
                expandExpDiv(title, text);
            }
            else {
                collapseExpDiv(title, text);
            }
        }
    }
}

   function OpenAndSetLocationDlg(divToOpenID,srcElm, align )
{    
    CloseAllMenus();    
   var dlgDiv = document.getElementById(divToOpenID);
	
    if (dlgDiv != null)
    {
    dlgDiv.style.display = "block";

    //the addition of Number + "px" is for FF
    var left ;
    if (align == 'left')
        left = Number(GetPosX(srcElm));
    else if (align == 'right')
        left = Number((GetPosX(srcElm) - (dlgDiv.offsetWidth - srcElm.offsetWidth )));

    if (IsIE8Browser())
    {
         left = left - 1;
    }	
    dlgDiv.style.left = left + "px";
	
    var top = Number(GetPosY(srcElm) + srcElm.offsetHeight );    
    if (IsIEBrowser())
    {
        top = top -1;
    }
    dlgDiv.style.top = top + "px";
    
    OpenDlg(dlgDiv,srcElm.id);    
    }
}
function OpenDlg(dlgDiv, srcElmID)
{    
    dlgDiv.style.display = "block"; 
    var srcElm = document.getElementById(srcElmID);
    if(srcElm != null)
    {
        var color;
	    try 
	    {    
		    color = dlgDiv.currentStyle.backgroundColor;
	    } 
	    catch(err) 
	    {    
		    color = document.defaultView.getComputedStyle(dlgDiv, '').getPropertyValue("background-color");
	    }	
	    srcElm.style.backgroundColor = color;
    }
}

function CloseDlg(dlgDiv,srcElmID) 
{   
	//alert('divToCloseID=' + divToCloseID);
	//if(event.srcElement.tagName == "DIV" && event.srcElement.id == divToCloseID)
	{
        //var dlgDiv= document.getElementById(divToCloseID);
		//dlgDiv.style.visibility = "hidden"; 
                       if (dlgDiv != null)
                             {
		dlgDiv.style.display = "none"; 
                             }
    } 
    /*else 
	{
        var txt = document.getElementById("debug");
		txt.innerText = txt.innerText+event.srcElement.tagName + ' ' + event.srcElement.id + ' ' ;
    }*/    
    
    var srcElm = document.getElementById(srcElmID);
    srcElm.style.backgroundColor = ''; 
    //alert('CloseDlg');
}

function CloseAllMenus()
{
    var divList,i;
    // loop through all images of the document
     divList=document.getElementsByTagName("div");
     for(i=0;i<divList.length;i++)
     {
        if (divList[i].className == "FloatDiv")
            divList[i].style.display = "none";
     }     
}

function GetPosX(obj)
{
	var curleft = 0;
	while (obj.offsetParent)
	{
	  curleft += obj.offsetLeft;
	  obj = obj.offsetParent;
	}
	return curleft;

}
function GetPosY(obj)
{
	var curtop = 0;
	while (obj.offsetParent)
	{
	  curtop += obj.offsetTop;
	  obj = obj.offsetParent;
	}
	return curtop;
}

//window.onload = function() {
//            var spRemoveEvent = document.getElementById('LinkDlgOpener');
//            spRemoveEvent.onmouseover = null;
//            spRemoveEvent.onmouseout = null;            
//        }


   addLoadEvent(function()
{     	  
     var a = document.getElementById('MenuSeparator')
     if (a != null)
     {      	  
        //debugger
		if (IsIEBrowser())
		{
			try
			{    	        
				var padding = parseInt(a.parentNode.currentStyle.paddingLeft) + parseInt(a.parentNode.currentStyle.paddingRight);
				a.style.width = a.parentNode.offsetWidth - padding;
			}
			catch(e)
			{   
    	        //a.style.width = a.parentNode.offsetWidth; 	    
			}
		}
		else
		{
			a.style.width="100%";
		}
    }
}); 

   /**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
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){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"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(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},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[_16.length]=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");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_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");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_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{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}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(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[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(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;


function getBanner(bannerID){
	return document.getElementById(bannerID);
}
		
function listening(bannerID){
          var flashInitFunc = bannerID + 'Init()';
          eval(flashInitFunc);
}
			
function ready(bannerID){
var version = '1.0';
try
{
version = eval(bannerID + 'FlashBannerVersion');
}
catch(err) {}
if ( version =='1.1'){
          var flashEl = document.getElementById(bannerID);
	bannerID = bannerID.replace("ID","");
         var el = document.getElementById(bannerID);
	nextObject(el).style.display='none';
   	el.style.width =flashEl.width;
	el.style.height =flashEl.height;
}
else{
          bannerID = bannerID.replace("ID","");
          var el = document.getElementById(bannerID);
          el.style.backgroundImage = "none";
}
}
		
function error(bannerID, id, value)
{
var version = '1.0';
try
{
version = eval(bannerID + 'FlashBannerVersion');
}
catch(err) {}
if (version=='1.1') {
         // show loader image in any error case - return it back to the front
        // In case of error id = 6 remain presenting the flash
        if(id != 6)
        {
	var el = document.getElementById(bannerID);
	el.style.display='none';
	nextObject(el).style.display='block';
        }
}
else {
         // show loader image in any error case - return it back to the front
        //alert("error (" + id + ")" + value);
        // In case of error id = 6 remain presenting the flash
        if(id != 6)
        {
                var bgIMGID = bannerID + "BG";
                var el = document.getElementById(bannerID);
                el.style.backgroundImage="url"+"('"+document.getElementById(bgIMGID).value+"')";
        }
}
}

function ExtendedJSLinkWithRegLink(link, unicaEvent, jsLink, sCut)
{
  var sURL = link;

  if (sCut != "")
  { 
    var pos = sURL.indexOf("?");
    if (pos < 0) // if link url doesn't contains '?' already
    {
      sURL += "?" + sCut;
    }
    else
    {
      sURL += "&" + sCut;
    } 
   }

	if (unicaEvent != null && unicaEvent != "")
	{
    try 
    {
      ntptEventTag("ev=" + unicaEvent);
    } catch (err) { }
	}	
	
	if (jsLink != null && jsLink != "")
	{
	  eval(jsLink);
	}	
		
	document.location.href = sURL;
}



function ExtendedJSLink(unicaEvent, jsLink)
{

	if (unicaEvent != null && unicaEvent != "")
	{
    try 
    {
      ntptEventTag("ev=" + unicaEvent);
    } catch (err) { }
	}	
	
	if (jsLink != null && jsLink != "")
	{
	   eval(jsLink);
	}	

}


function ExtendedRegularLink(link, unicaEvent, sCut)
{

  var sURL = link;

  if (sCut != "")
  { 
    var pos = sURL.indexOf("?");
    if (pos < 0) // if link url doesn't contains '?' already
    {
      sURL += "?" + sCut;
    }
    else
    {
      sURL += "&" + sCut;
    } 
   }
	
	if (unicaEvent != null && unicaEvent != "")
	{
    try 
    {
      ntptEventTag("ev=" + unicaEvent);
    } catch (err) { }
	}	
  
	
   document.location.href = sURL;
}


function ExtendedRegularLinkNewWindow(link, unicaEvent, sCut)
{
	var sURL = link;
	
  if (sCut != "")
  { 
    var pos = sURL.indexOf("?");
    if (pos < 0) // if link url doesn't contains '?' already
    {
      sURL += "?" + sCut;
    }
    else
    {
      sURL += "&" + sCut;
    } 
   }
	
	if (unicaEvent != null && unicaEvent != "")
	{
    try 
    {
      ntptEventTag("ev=" + unicaEvent);
    } catch (err) { }
	}	
	
	window.open(sURL);
}

function nextObject (obj) { 
var n = obj; 
do n = n.nextSibling; 
while (n && n.nodeType != 1); 
return n; 
} 

   function OpenChat(){	startChatWithEscalation('8o8QZZ1050123', 'chat.cassava.net', 'CUSTOMER', null, null, null);}

/////////////////////////////////////////////////
//                                             //
//  KANA Response Live Functions               //
//  Version $Revision: 1.1 $                  //
//                                             //
//  Copyright (c) 2004 - KANA Inc.    		   //
//  All Rights Reserved.  Patent Pending.      //
//                                             //
/////////////////////////////////////////////////

//===================================================================
// Default IChannel And Server locations
// 1. Set the gIChannelID value to be the value of your default iChannel.
// 2. If you have an on-premise solution, set the gServer value to be
// the fully qualified domain name of the web server running KANA Response Live.
//===================================================================
var gIChannelID = "Default";
var gServer = "router.conavigator.com";

//===================================================================
// startMeetMe launches the basic Conav application w/o DSP
//
// IChannelID: IChannelID for interaction
// AttachedData: Company-specific data to attach to customer's acocunt
// CustomerName: the name of the customer requesting live help
// ConenctToName: the id of the rep to whom the customer is connecting
//===================================================================
function startMeetMe(iChannelID, attachedData, customerName, connectToName, server) {
	window.startVarApp = startConavVarApp;
	window.getWinProperties = getConavWinProperties;
	setServerDomain(server);
	setCustomerName(customerName);
	setConnectToName(connectToName);
	launchRegularStartPage(iChannelID, attachedData);
}


//===================================================================
// startDSPMeetMe launches the Conav application using Dynamic Start Page
//
// IChannelID: IChannelID for interaction
// AttachedData: Company-specific data to attach to customer's acocunt
// CustomerName: the name of the customer requesting live help
// ConenctToName: the id of the rep to whom the customer is connecting
//===================================================================
function startDSPMeetMe(iChannelID, attachedData, customerName, connectToName, server) {
	window.startVarApp = startConavVarApp;
	window.getWinProperties = getConavWinProperties;
	setServerDomain(server);
	setCustomerName(customerName);
	setConnectToName(connectToName);
	launchDynamicStartPage(iChannelID, attachedData);
}



//===================================================================
// startDirectCall launches the Direct Call application
//
// IChannelID: IChannelID for interaction
// AttachedData: Company-specific data to attach to customer's acocunt
//===================================================================
function startDirectCall(iChannelID, attachedData, server) {
	window.startVarApp = startDirectCallVarApp;
	window.getWinProperties = getCallbackWinProperties;
	setServerDomain(server);
	launchDynamicStartPage(iChannelID, attachedData); 	
}


//===================================================================
// startCallback launches the Basic Callback application
//
// IChannelID: IChannelID for interaction
// AttachedData: Company-specific data to attach to customer's acocunt
//===================================================================
function startCallback(iChannelID, attachedData, server) {
	window.startVarApp = startCallbackVarApp;
	window.getWinProperties = getCallbackWinProperties;
	setServerDomain(server);
	launchDynamicStartPage(iChannelID, attachedData);
}


//===================================================================
// startCallbackExtended launches the Callback application for a given
// customer telephone number.
//
// IChannelID: IChannelID for interaction
// AttachedData: Company-specific data to attach to customer's acocunt
// customerName: name of the customer
// telephoneNumber: Telephone number
// countryCode:  Telephone Country Code
//
//===================================================================
function startCallbackExtended(iChannelID, attachedData, customerName, telephoneNumber, countryCode, server) {
	window.gTelephoneNumber = telephoneNumber;
	window.gCountryCode = countryCode;
	window.gCustomerName = customerName;
	window.startVarApp = startCustomCallbackVarApp;
	window.getWinProperties = getCallbackWinProperties;
	setServerDomain(server);
	launchDynamicStartPage(iChannelID, attachedData);
}


//====================================================================================
//====================================================================================
//====================================================================================
// Private Functions and variables for KANA Use Only
// Do not modify or call these functions.
//====================================================================================
//====================================================================================
//====================================================================================

var gHelpWindow = "help";
var gLaunchUrl;
var gAttachedData;
var gConnectToName = "";
var gCustomerName = "";
var gAppType = "";
var gConavHtdocsPath = "/CONAV/HTD/";
var gHTTP = "http://";
var gHTTPS = "https://";

function setIChannelID(iChannelID) {
	if(typeof(iChannelID) == "undefined" || iChannelID == null)
		return;

	window.gIChannelID = iChannelID;
}

function getIChannelID() {
	return window.gIChannelID;
}

function setServerDomain(server) {
	if(typeof(server) == "undefined" || server == null )
		return;

	window.gServer = server;
}

function getServerDomain() {
	return window.gServer;
}

function setLaunchUrl(url) {
	window.gLaunchUrl = url;
}

function getLaunchUrl() {
	return window.gLaunchUrl;
}

function getHelpWindowName() {
	return window.gHelpWindow;
}

function setConnectToName(connectToName) {
	if(typeof(connectToName) == "undefined" || connectToName == null)
		return;

	window.gConnectToName = connectToName;
}

function getConnectToName() {
	return window.gConnectToName;
}

function setCustomerName(customerName) {
	if(typeof(customerName) == "undefined" || customerName == null)
		return;

	window.gCustomerName = customerName;
}

function getCustomerName() {
	return window.gCustomerName;
}

function setAttachedData(attachedData) {
	window.gAttachedData = attachedData;
}

function getAttachedData() {
	return window.gAttachedData;
}

function getConavHtdocsPath() {
	return window.gConavHtdocsPath;
}

function launchRegularStartPage(iChannelID, attachedData) {
	launchStartPage(iChannelID, attachedData, "invokeRegularStartPage()");
}

function launchDynamicStartPage(iChannelID, attachedData) {
	launchStartPage(iChannelID, attachedData, "invokeDynamicStartPage()");
}

function launchStartPage(iChannelID, attachedData, launchFunctionStr) {
	setIChannelID(iChannelID);
	setAttachedData(attachedData);

	//the ssl check cannot be made with opera 5.
	if( window.location.protocol == "http:" && !isOpera() ) {
		checkSSLEnabled(launchFunctionStr);
	}
	else {
		eval(launchFunctionStr);
	}
}

function checkSSLEnabled(launchFunctionStr) {
	var testImg = new Image(1,1);
	testImg.onerror = new Function("handleNoSSL()");
	testImg.onload = new Function(launchFunctionStr);
	testImg.src = gHTTPS + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/shared/images/blank.gif?time=" + (new Date()).getTime();
}

function invokeDynamicStartPage() {
	if(typeof(isHipboneSharedWindow) != "undefined") {
		launchRecursiveErrorMessage();
		return;
	}

	if(isMacButNotNetscape()) {
		startVarApp();
		return;
	}

	var link = "responseLiveLauncher.html?ichannel=" + escape(getIChannelID()) + "&host=" + escape(getServerDomain()) + "&apptype=" + gAppType + getAttachedDataQueryParam();
	launchWindow(link);
}

function invokeRegularStartPage() {
	if(typeof(isHipboneSharedWindow) != "undefined") {
		launchRecursiveErrorMessage();
		return;
	}

	startVarApp();
}

function startConavVarApp() {
	var link = gHTTPS + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/StartConavPage?time=" + (new Date()).getTime() + "&NAME=" + escape(getCustomerName()) + "&CONNECT_TO=" + escape(getConnectToName()) + getAccountSpecificQueryParam();
	launchWindow(link);
}

function startDirectCallVarApp() {
	var link = gHTTPS + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/login/oem/callback/n_to_p.thtml?METHOD=phoneCallBack.thtml";
	launchWindow(link);
}

function startCallbackVarApp() {
	var link = gHTTPS + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/login/oem/callback/n_to_p.thtml";
	launchWindow(link);
}

function startCustomCallbackVarApp() {
	var link = gHTTPS + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/login/oem/callback/n_to_p.thtml?"
   	+ "PHONE_NUMBER=" + escape(gTelephoneNumber)
   	+ "&COUNTRY_CODE=" + escape(gCountryCode)
   	+ "&CUSTOMER_NAME=" + escape(gCustomerName)
   	+ "&TIME=" + (new Date()).getTime();
	launchWindow(link);
}

function launchRecursiveErrorMessage() {
	var link = gHTTP + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/login/recursiveConav.thtml";
	launchWindow(link);
}

function handleNoSSL() {
	var link = gHTTP + getServerDomain() + getConavHtdocsPath() + getIChannelID() + "/login/sslDisabled.thtml";
	launchWindow(link);
}

function getConavWinProperties() {
	return 'scrollbars=yes,resizable=' + (isNetscape()?'no':'yes') + ',width=270,height=400,screenX=10,screenY=10,top=10,left=10';
}

function getCallbackWinProperties() {
	return 'scrollbars=yes,resizable=' + (isNetscape()?'no':'yes') + ',width=300,height=430,screenX=10,screenY=10,top=10,left=10';
}

function getAttachedDataQueryParam() {
	var attachedDataQStr = "";
	if(getAttachedData()) {
		attachedDataQStr = "&ATTACHED_DATA=" + escape(getAttachedData());
	}

	return attachedDataQStr;
}

function getAccountSpecificQueryParam() {
	var attachedDataQStr = "";
	if(getAttachedData()) {
		attachedDataQStr = "&ACCTSPECIFIC=" + escape(getAttachedData());
	}

	return attachedDataQStr;
}

//===================================================================
// AOL-safe window.open()
//===================================================================

function launchWindow(launchUrl) {
	setLaunchUrl(launchUrl);
	if(isAOL()) {
		var scriptletHTML = "<object data='responseLiveScriptletLauncher.html' type='text/x-scriptlet' width=0 height=0></object>";
		document.body.insertAdjacentHTML('BeforeEnd', scriptletHTML);
		return;
	}

	window.open(getLaunchUrl(), getHelpWindowName(), getWinProperties());
}

function isNetscape() {
	return (navigator.appName.indexOf("Netscape")!=-1);
}

function isAOL() {
	return (navigator.appVersion.indexOf("AOL")!=-1);
}

function isOpera() {
	return (navigator.userAgent.indexOf("Opera")>-1);
}

function isMac() {
	return (navigator.userAgent.indexOf("Mac")>-1);
}

function isMacButNotNetscape() {
	return (isMac() && !isNetscape());
}

/////////////////////////////////////////////////
//                                             //
//  KANA Response Live Chat Functions          //
//  Version $Revision: 1.1 $                  //
//                                             //
//  Copyright (c) 2004 - KANA Inc.    		   //
//  All Rights Reserved.  Patent Pending.      //
//                                             //
/////////////////////////////////////////////////


//======================================================================
// Uncomment and set gAfterLaunchURL to the url of the page you want
// to display after launching live help chat
//======================================================================
//var gAfterLaunchURL="http://www.kana.com";

var gChatWindowWidth = 300;
var gChatWindowHeight = 500;
var gChatWindowProperties = "width=" + gChatWindowWidth + ",height=" + gChatWindowHeight + ",menubar=no,location=no,directories=no,status=no,toolbar=no,scrollbars=auto,resizable=yes,screenX=10,screenY=10,left=10,top=10";
var gDSPLauncherPageName = "responseLiveLauncher.html";
var gHTTP = "http://";
var gHTTPS = "https://";

function startChat(iChannel, server_name, attached_data, custom_values, agent_only_values, go_immediately_into_queue)
{
	var chatLaunchMode = "CHAT_ONLY";
	launchChat(iChannel, server_name, attached_data, custom_values, agent_only_values, go_immediately_into_queue, chatLaunchMode);
}

function startChatAndCobrowse(iChannel, server_name, attached_data, custom_values,agent_only_values, go_immediately_into_queue)
{
	var chatLaunchMode = "COBROWSE";
	launchChat(iChannel, server_name, attached_data, custom_values, agent_only_values, go_immediately_into_queue, chatLaunchMode);
}

function startChatWithEscalation(iChannel, server_name, attached_data, custom_values,agent_only_values, go_immediately_into_queue)
{
	var chatLaunchMode = "COBROWSE_ESCALATION";
	launchChat(iChannel, server_name, attached_data, custom_values, agent_only_values, go_immediately_into_queue, chatLaunchMode);
}

function launchChat(iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode)
{
	if (isAOL())
	{
		saveChatParamaters(window, iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode);
		var scriptletHTML = "<object data='responseLiveLauncher.html' type='text/x-scriptlet' width=0 height=0></object>";
		document.body.insertAdjacentHTML('BeforeEnd', scriptletHTML);
		return;
	}

	openInitialWindow();
	finishLaunchingChat(iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode)
}

function finishLaunchingChat(iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode)
{
	var chatWin = getChatWindow();
	saveChatParamaters(chatWin, iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode);

	if (alreadyConavigating())
	{
		handleRecursiveLaunch(iChannel, serverName, chatWin);
		return;
	}

	if (browserDoesNotSupportDOM2() || isIEonMac())
	{
		handleUnsupportedBrowser(iChannel, serverName, chatWin);
		return;
	}

	if (!areCookiesEnabled())
	{
		handleDisabledCookies(iChannel, serverName, chatWin);
		return;
	}

	if(window.location.protocol == "https:")
		createAndSubmitForm();
	else
		checkSSLEnabledAndSubmit(iChannel, serverName);
}

function createAndSubmitForm()
{
	var chatWin = getChatWindow();
	var launchChatForm = createForm(chatWin.serverName, chatWin);

	// add this parameter to use dsp
	addFormField(launchChatForm, chatWin, "DSP_LAUNCHER_PAGE_NAME", gDSPLauncherPageName);
	addFormField(launchChatForm, chatWin, "CHAT_WINDOW_WIDTH", gChatWindowWidth);
	addFormField(launchChatForm, chatWin, "CHAT_WINDOW_PROPERTIES", gChatWindowProperties);
	addFormField(launchChatForm, chatWin, "ICHANNEL_ID", chatWin.iChannel);
	addFormField(launchChatForm, chatWin, "ATTACHED_DATA", chatWin.attachedData);
	addFormField(launchChatForm, chatWin, "ENTER_ON_QUEUE_PAGE", chatWin.enterOnQueuePage);
	addFormField(launchChatForm, chatWin, "CHAT_LAUNCH_MODE", chatWin.chatLaunchMode);
	addFormField(launchChatForm, chatWin, "AGENT_VISIBLE_DATA", createAgentVisibleDataString(chatWin.agentOnlyValues));

	var prefillValues = chatWin.prefillValues;
	for (prefillItem in prefillValues)
	{
		addFormField(launchChatForm, chatWin, prefillItem, prefillValues[prefillItem]);
	}

	launchChatForm.submit();
}

function openInitialWindow()
{
	var newWin = window.open("", getChatWindowName(), getWinProperties());
	newWin.document.write("<html><head><title>Live Chat</title></head><body></body></html>");
	newWin.document.close();
	setChatWindow(newWin);
}

function createForm(serverName, win)
{
	var launchChatForm = win.document.createElement("form");
	launchChatForm.method = "post";
	launchChatForm.target = "_self";
	launchChatForm.action = gHTTPS + serverName + "/CONAV/CHAT/ChatPreLaunch";
	win.document.body.appendChild(launchChatForm);
	return launchChatForm;
}

var DATA_SEPARATOR = "_HB_";
function createAgentVisibleDataString(agentOnlyValues)
{
	var agentVisibleData = "";
	for (agentItem in agentOnlyValues)
	{
		if(isNonEmptyString(agentVisibleData))
			agentVisibleData += DATA_SEPARATOR;

		agentVisibleData += agentItem + DATA_SEPARATOR + agentOnlyValues[agentItem];
	}
	return agentVisibleData;
}

function addFormField(launchChatForm, win, name, value)
{
	if(!isNonEmptyString(name) || !isNonEmptyString(value))
		return;
	var elementObj = win.document.createElement("input");
	elementObj.type = "hidden";
	elementObj.name = name;
	elementObj.value = value;
	launchChatForm.appendChild(elementObj);
}

function alreadyConavigating()
{
	return (typeof(isHipboneSharedWindow) != "undefined");
}

function handleRecursiveLaunch(iChannel, serverName, win)
{
	win.location.href = gHTTPS + serverName + "/CONAV/chat/errorpages/recursiveConav.jsp?ICHANNEL_ID=" + iChannel;
}

function browserDoesNotSupportDOM2()
{
	return (null == document.getElementById);
}

function handleUnsupportedBrowser(iChannel, serverName, win)
{
	win.location.href = gHTTPS + serverName + "/CONAV/CHAT/ChatPreLaunch?ICHANNEL_ID=" + iChannel;
}

function areCookiesEnabled()
{
	var time = (new Date()).getTime();
	setTestCookie(time);
	if (theCookieIsSet(time))
	{
		removeTestCookie(time);
		return true;
	}
	return false;
}

function setTestCookie(value)
{
	document.cookie = "hbcookietest=" + value;
}

function theCookieIsSet(value)
{
	var theCookieString = document.cookie;
	return (isNonEmptyString(theCookieString) && theCookieString.indexOf(value) > -1);
}

function removeTestCookie(value)
{
	document.cookie = "hbcookietest=" + value + "; expires=Fri, 02-Jan-1970 00:00:00 GMT";
}

function handleDisabledCookies(iChannel, serverName, win)
{
	win.location.href = gHTTP + serverName + "/CONAV/chat/errorpages/cookiesDisabled.jsp?ICHANNEL_ID=" + iChannel;
}

function checkSSLEnabledAndSubmit(iChannel, serverName)
{
	createAndSubmitForm();
	var testImg = new Image(1,1);
	testImg.onerror = function() { handleChatNoSSL(iChannel, serverName); }
	testImg.src = gHTTPS + serverName + "/CONAV/HTD/Default/shared/images/blank.gif?time=" + (new Date()).getTime();
}

function handleChatNoSSL(iChannel, serverName)
{
	var link = gHTTP + serverName + "/CONAV/chat/errorpages/sslDisabled.jsp?ICHANNEL_ID=" + iChannel;
	window.open(link, getChatWindowName(), getWinProperties());
	getChatWindow().close();
}

function saveChatParamaters(chatWin, iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode)
{
	chatWin.iChannel = iChannel;
	chatWin.serverName = serverName;
	chatWin.attachedData = attachedData;
	chatWin.prefillValues = prefillValues;
	chatWin.agentOnlyValues = agentOnlyValues;
	chatWin.enterOnQueuePage = enterOnQueuePage;
	chatWin.chatLaunchMode = chatLaunchMode;
}

function setAOLChatWindow(chatWin)
{
	setChatWindow(chatWin);
	with (window)
	{
		finishLaunchingChat(iChannel, serverName, attachedData, prefillValues, agentOnlyValues, enterOnQueuePage, chatLaunchMode);
	}
}

var gChatLaunchWindow = null;
function setChatWindow(chatWin)
{
	window.gChatLaunchWindow = chatWin;
}

function getChatWindow()
{
	return window.gChatLaunchWindow;
}

function getChatWindowName()
{
	return "_blank";
}

function getWinProperties()
{
	return gChatWindowProperties;
}

function isAOL()
{
	return (navigator.appVersion.toLowerCase().indexOf("aol")!=-1);
}

function isIE()
{
    return (navigator.userAgent.toLowerCase().indexOf("msie")!=-1);
}

function isMac()
{
	return (navigator.userAgent.toLowerCase().indexOf("mac")!=-1);
}

function isIEonMac()
{
    return (isIE() && isMac())
}

function isNonEmptyString(str)
{
	if(null == str || str == "")
		return false;
	return true;
}

function goToAfterLaunchUrl() 
{
    if(typeof(window.gAfterLaunchURL) == "undefined")
		return;

	window.location.href = window.gAfterLaunchURL;
}


   function OpenRightNow(url)
{
//      var w = 580;
//      var h = 700;
//      var l = (window.screen.width-w)/2;
//      var t = (window.screen.height-h)/2;
//      window.open(url,"faq","resizable=no,status=no,scrollbars=yes,toolbar=no,menubar=no,left=" + l + ",top=" + t + ",width=" + w + ",height=" + h);
//      window.open(url, 'faq');

windowFeatures = "scrollbars=1,top=0,left=0,resizable=yes,width="+(screen.width)+",height="+(screen.height); 
newWindow=window.open(url,'faq',windowFeatures)
newWindow.focus(); 
}


function OpenRightNow888(){OpenRightNow("http://888-external-dk.custhelp.com/app/home/prod/1/");}
function OpenRightNowPoker(){OpenRightNow("http://888-external-dk.custhelp.com/app/home/prod/4/");}
function OpenRightNowCasino(){OpenRightNow("http://888-external-dk.custhelp.com/app/home/prod/1/");}
function OpenRightNowBingo(){OpenRightNow("http://888-external-en.custhelp.com/app/home/prod/234/");}
function OpenRightNowSport(){OpenRightNow("http://888-external-dk.custhelp.com/app/home/prod/243/");}
function OpenRightNowGames(){OpenRightNow("http://888-external-en.custhelp.com/app/home/prod/257/");}


   function OpenNRS() {
    if (arguments.length >= 7 && sTestDataXML.length > 0 && sNRSDomain.length > 0) {
        // appending mandatory parameters
        var targetURL = sNRSDomain + "?" + "rl=" + arguments[0] +
                                "&brand=" + arguments[1] + "&version=" + arguments[2] + "&orientation=" + arguments[3] +
                                "&subbrand=" + arguments[4] + "&mode=" + arguments[5] + "&platform=" + arguments[6];
        // appending non-mandatory parameters
        if (nSerial.length > 0) {
            // appending the language from session
            targetURL += "&sr=" + nSerial;
        }

        // appending non-mandatory parameters
        if (arguments[7] != null) {
            // appending the language from input parameters
            targetURL += "&lang=" + arguments[7];
        }
        else if (sLanguage.length > 0) {
            // appending the language from session
            targetURL += "&lang=" + sLanguage;
        }
        if (arguments[8] != null) {
            // appending the skin parameter
            targetURL += "&skin=" + arguments[8];
        }
        // appending the test data xml
        targetURL += "&testdata=" + sTestDataXML;
        // opening the NRS page in separate window
        window.open(targetURL.toLowerCase(), "NRSPage", "status=1, location=1, resizable=1", false);
    }
    return false;
}

   function reportAcquisitionChannel(i_acq) {
  var category = 'acquisition/' + i_acq;
  var action = 'view' + (location.href.indexOf('http://stage-') == 0 ? '-stage' : '');
  
  try {
    // 1st parameter is the slot number
    // 4th parameter is the score (1 for visitor, 2 for session, 3 for page)
    pageTracker._setCustomVar(1, 'Acquisition Channel', i_acq, 2);
    pageTracker._trackEvent(category, action);
  }
  catch (err) { }  
}

if (typeof rlWtv == 'string' && rlWtv == 'mbindictmp') {
  if (typeof addLoadEvent == 'function') {
    addLoadEvent(function() {
      reportAcquisitionChannel('mb');
    });
  }
}

   /////
// Check retargeting_bit bit (6th bit of the Flag parameter)
if (typeof rlFlag == 'string' && rlFlag.charAt(5) != '1') {
  var retargeting_bit = {
    'tag_id' : null, // default tag id
    'tags_map' : {
      '888.com' : 'B3441490.9',
      '888poker.com' : 'B3441490.7',
      '888casino.com' : 'B3441490.8'
    },
    'random_timestamp' : ((Math.random() + "") * 1000000000000000000),
    'anid' : (typeof rlAnid == 'string' ? rlAnid : '')
  }
  
  for (var domain in retargeting_bit.tags_map) {
    if (window.location.hostname.indexOf(domain) >= 0) {
      retargeting_bit.tag_id = retargeting_bit.tags_map[domain];
      break;
    }
  }
    
  if (retargeting_bit.tag_id && 'createElement' in document) {
    retargeting_bit.iframe = '<IFRAME SRC="http://ad.doubleclick.net/adi/N1684.Sites/' + retargeting_bit.tag_id + ';sz=1x1;anid=' + retargeting_bit.anid + ';click=;ord=' + retargeting_bit.random_timestamp + '?" WIDTH=1 HEIGHT=1 MARGINWIDTH=0 MARGINHEIGHT=0 HSPACE=0 VSPACE=0 FRAMEBORDER=0 SCROLLING=no BORDERCOLOR="#000000"><SCR' + 'IPT language="JavaScript1.1"; SRC="http://ad.doubleclick.net/adj/N1684.Sites/B3441490.9;abr=!ie;sz=1x1;anid=' + retargeting_bit.anid + ';click=;ord=' + retargeting_bit.random_timestamp + '?"></SCR'+'IPT></IFRAME>';
    retargeting_bit.div = document.createElement('div');
    retargeting_bit.div.innerHTML = retargeting_bit.iframe;
    addLoadEvent(function () {
      if ('body' in document && 'appendChild' in document.body) {
        document.body.appendChild(retargeting_bit.div);
      }
    });
  }  
}

   
var entry_popup = {
  'blocked_agents': ['sunos', 'unix', 'linux'],  
  
  'wrapper_element' : null,
  'popup_element' : null,
  'overlay_element' : null,
  'map_element' : null,
  'image_obj' : null,
  
  'state' : 'initial',
  
  'init' : function () {
    entry_popup.load_image();
    addLoadEvent(function () { entry_popup.create(); });
  },
  
  'load_image' : function () {
    if (entry_popup_data && 'image' in entry_popup_data) {
      var img = new Image();
      img.src = entry_popup_data.image;
      entry_popup.image_obj = img;
    }
  },

  'create' : function () {
    if (!('createElement' in document) || entry_popup.isBlockedByUserAgent() || entry_popup.isBlockedByFlag()) {
      return;
    }
    
    var cookie_name = 'cookie_name' in entry_popup_data ? entry_popup_data.cookie_name : 'show_entry_popup';
    if (document.cookie.indexOf(cookie_name) < 0) {
      var date = new Date();
      date.setTime(date.getTime() + 7200000);
      document.cookie = cookie_name + '=0; expires=' + date.toGMTString() + ' ;path=/';
    }
    else if (!('use_cookie' in entry_popup_data) || (entry_popup_data.use_cookie)) {
      return;
    }
    
    var wrapper_element = document.createElement('div');
    wrapper_element.id = 'entry_popup_wrapper';
    
    // Create overlay (black screen)
    if (entry_popup_data.show_overlay) {
      var overlay_element = document.createElement('div');
      overlay_element.id = 'entry_popup_overlay';
      overlay_element.innerHTML = '&nbsp;';
      wrapper_element.appendChild(overlay_element);
      entry_popup.overlay_element = overlay_element;
    }
    
    // Create the map
    if ('map' in entry_popup_data && entry_popup_data.map.length > 0) {
      var map_element = document.createElement('map');
      setAttribute(map_element, 'name',  'entry_popup_map');
      setAttribute(map_element, 'id',  'entry_popup_map');
      for (var area_index in entry_popup_data.map) {
        var area_element = document.createElement('area');
        for (var attr_key in entry_popup_data.map[area_index]) {
          var attr_value = entry_popup_data.map[area_index][attr_key];
          if (attr_key.indexOf('on') == 0 && typeof attr_value == 'function') {
            addEvent(area_element, attr_key.substr(2), attr_value, false);
          }
          else {
            setAttribute(area_element, attr_key, attr_value);
          }
        }
        map_element.appendChild(area_element);
      }
      wrapper_element.appendChild(map_element);
      entry_popup.map_element = map_element;
    }
    
    // Create popup element
    var popup_element = document.createElement('div');
    popup_element.id = 'entry_popup';
    popup_element.style.marginLeft = '-' + (entry_popup_data.width / 2) + 'px';
	
    // Create image inside the popup
    var img_element = document.createElement('img');
    img_element.src = entry_popup.image_obj.src;
    img_element.border = '0';
    if (entry_popup.map_element != null) {
      img_element.useMap = '#entry_popup_map';
    }
    popup_element.appendChild(img_element);
    entry_popup.popup_element = popup_element;
    wrapper_element.appendChild(popup_element);
    
    entry_popup.wrapper_element = wrapper_element;
    document.body.appendChild(wrapper_element);	
    setTimeout(entry_popup.open, entry_popup_data.timeout_interval);
  },
  
  'open' : function () {
    if (entry_popup.image_obj.complete && entry_popup.image_obj.width > 0) {
      if (entry_popup.wrapper_element != null && entry_popup.popup_element != null) {
        addEvent(window, 'resize', entry_popup.resize);
        entry_popup.resize();
        entry_popup.wrapper_element.style.visibility = 'visible';
        entry_popup.state = 'opened';
        if (IsIEBrowser() && 'scrollTo' in window) {
          window.scrollTo(0, 0);
        }
      }
    }
    else {
      setTimeout(entry_popup.open, 3000);
    }
  },
  
  'close' : function ()  {
    if (entry_popup.wrapper_element != null) {
      entry_popup.wrapper_element.style.display = 'none';
      entry_popup.state = 'closed';
    }
  },
  
  'resize' : function () {
    if (entry_popup.state == 'opened' || entry_popup.state == 'initial') {
      entry_popup.wrapper_element.style.display = 'none';
      var height = document.body.clientHeight;
      
      if (entry_popup.overlay_element != null) {
        entry_popup.overlay_element.style.height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) + 'px';
      }
      entry_popup.popup_element.style.top = ((Math.max(entry_popup_data.height + 100, height) - entry_popup_data.height) / 2) + 'px';
      entry_popup.wrapper_element.style.display = 'block';
    }
  },
  
  'close_handler' : function (e) {
    e = typeof e == 'undefined' ? window.event : e;
    
    if (e) {
      if ('cancelBubble' in e) {
        e.cancelBubble = true;
        e.returnValue = false;
      }
      if ('stopPropagation' in e) {
        e.stopPropagation();
        e.preventDefault();
      }
    }
    entry_popup.close();
    return false;
  },
  
  'isBlockedByUserAgent' : function () {
    var res = false;
    var userAgent = navigator.userAgent.toLowerCase();
    for (index in entry_popup.blocked_agents) {
      if (userAgent.indexOf(entry_popup.blocked_agents[index]) > -1) {
        res = true;
        break;
      }
    }
    return res;
  },
  
  'isBlockedByFlag' : function () {
    var res = false;
    if (typeof rlFlag == 'string' && rlFlag.charAt(0) == '1') {
      res = true;
    }
    return res;
  }
};

   
var conversion = (function () {
  // the public module we'll be returning
  var me = {
    // public vars
    is_running : false
  };
  
  // private vars
  var st = null,          // mkw and st parameters
      mkw = null,
      is_stage = location.href.indexOf('http://stage-') == 0;
  
  // consts vars
  var c_cookie_name = 'conversion_data',
      c_branded_domains = [
        '.888.com', '.888casino.com', '.888poker.com',
        '.reefclubcasino.com', '.eurocitycasino.com'
      ];
      
  /**
   * define private functions
   */
  
  // review the conversion_data object
  var m_check_valid_parameters = function() {
    var is_valid = true;
    is_valid = is_valid && 'test_id' in conversion_data && conversion_data.test_id;
    is_valid = is_valid && 'phase' in conversion_data && conversion_data.phase;
    is_valid = is_valid && 'combination' in conversion_data && conversion_data.combination;
    is_valid = is_valid && 'st' in conversion_data && conversion_data.st;
    
    is_valid = is_valid && ((conversion_data.type == 'optimizer' && 'trackcode' in conversion_data && conversion_data.trackcode.match(/^\d{9,}$/)) || (conversion_data.type == 'conversion'));
    
    return is_valid;
  };
  
  // Always return a sane type
  var m_sanitize_type = function () {
    var type = 'conversion';
    if ('type' in conversion_data) {
      switch (conversion_data.type) {
        case 'optimizer':
          type = conversion_data.type;
          break;
        default:
          break;
      }
    }
    return type;
  };
  
  var m_create_mkw = function () {
    mkw = conversion_data.st;
    
    var mkw_remove_regex = /&mkw=[^&]*&/i;
    if (typeof sCut == 'string') {
      sCut = sCut.replace(mkw_remove_regex, '&');
    }
  };

  var m_create_st = function () {
    try {
      var _st = parseInt(conversion_data.st);
      if (!isNaN(_st)) {
        st = _st.toString();
      }
    }
    catch (err) {
      st = null;
    }
    
    var st_regex_remove = /&st=[^&]*&/i;
    if (typeof sCut == 'string') {
      sCut = sCut.replace(st_regex_remove, '&');
    }
  };
  
  // Retreive the conversion_data object from the cookie
  // Tag the object as 'from_cookie'
  var m_get_data_from_cookie = function() {
    var conversion_data = {};
    var cookie_conversion_data = getCookie(c_cookie_name);
    if (cookie_conversion_data != null) {
      var data_arr = cookie_conversion_data.split('&');
      for (var i in data_arr) {
        var pair = data_arr[i].split('=');
        if (pair.length > 1 && pair[0]) {
          conversion_data[pair[0]] = pair[1];
        }
      }
      conversion_data['from_cookie'] = true;
    }
    return conversion_data;
  };
  
  // Sets the conversion_data object to the cookie
  var m_set_data_to_cookie = function() {
    var conversion_str = '';
    var conversion_arr = [];
    for (var key in conversion_data) {
      if (typeof conversion_data[key] != 'function') {
        if (key == 'from_cookie') {
          continue;
        }
        conversion_arr.push(key + '=' + conversion_data[key]);
      }
    }        
    conversion_str = conversion_arr.join('&');
        
    var date = new Date();
    date.setTime(date.getTime() + 7200000);
    setCookie(c_cookie_name, conversion_str, '/', date);    
  };

  var m_is_branded = function(host) {
    // assume branded, because its relative (and this scripts runs on branded sites)
    var is_branded = true;

    // fix for IE which decides to let host be with port
    if (host.indexOf(':') > 0) {
      host = host.substr(0, host.indexOf(':'));
    }
    
    // check if its an external link
    if (host != location.host) {
      // assume not branded, then check if its branded
      is_branded = false;
      // iterate over c_branded_domains and see if the domain is branded
      for (var i = 0; (i < c_branded_domains.length) && !is_branded; ++i) {
        is_branded = host.indexOf(c_branded_domains[i]) >= 0;
      }
    }
    return is_branded;
  };
  
  var m_alter_external_links = function () {
    if (!st || !mkw) { return; }
    
    var anchors = document.getElementsByTagName('a');
    for (var i = 0; i < anchors.length; ++i) {
      var item = anchors[i];
      if (item.host && m_is_branded(item.host)) {
        var has_query = item.href.indexOf('?') > 0;
        
        if (item.href.indexOf('st=') > 0) {
          item.href = item.href.replace(/([\?&]st=)[^&]*/, '$1' + st);
        }
        else {
          item.href += me.getSt(has_query);
        }
        
        if (item.href.indexOf('mkw=') > 0) {
          item.href = item.href.replace(/([\?&]mkw=)[^&]*/, '$1' + mkw);          
        }
        else {
          item.href += me.getMkw(true);
        }
      }
    }
  };
  
  /**
   * Public functions
   */
  
  // Initialize the whole shabang
  me.init = function() {
    // if data not present, get it from the cookie
    if (!('conversion_data' in window)) {
      var data_from_cookie = m_get_data_from_cookie();
      if (!isEmpty(data_from_cookie)) {
        window.conversion_data = data_from_cookie;
      }
    }
    
    // check if conversion data is valid and conversion is running
    if ('conversion_data' in window) {
      me.is_running = 'is_running' in conversion_data && conversion_data.is_running;
      
      // check and set default type for the experiment
      conversion_data.type = m_sanitize_type();
      
      if (me.is_running && m_check_valid_parameters()) {
        m_create_st();
        m_create_mkw();
        
        // Alter all external links if this is the first time the user has landed
        if (!conversion_data.from_cookie) {
          m_alter_external_links();
        }
      }
      
      if (!('from_cookie' in conversion_data && conversion_data.from_cookie)) {
        if (conversion_data.type == 'conversion') {
          this.reportConversionTest();
        }
        m_set_data_to_cookie();

        // Maybe the conversion_data has another specific init stuff
        if ('init' in conversion_data && typeof conversion_data.init == 'function') {
          conversion_data.init();
        }
      }
    }
  };
  
  me.getMkw = function (has_query) {
    var sign = '&'
    if (typeof has_query != 'undefined' && !has_query) {
      sign = '?';
    }
    
    return (mkw ? (sign + 'mkw=' + mkw) : '');
  };
    
  me.getSt = function (has_query) {
    var sign = '&'
    if (typeof has_query != 'undefined' && !has_query) {
      sign = '?';
    }
    
    return (st ? (sign + 'st=' + st) : '');
  };

  me.reportConversionTest = function () {    
    var action = 'test' + (is_stage ? '-stage' : '');
    try {
  	  if ('pageTracker' in window && '_trackEvent' in pageTracker && mkw != '') {
  	    var category = 'conversion/testid' + conversion_data.test_id + '_phase' + conversion_data.phase + '/' + conversion_data.combination;
        pageTracker._trackEvent(category, action);
  	  }
    } catch (err) { }
  };
  
  // Report the goal as a Google Optimizer goal, or as a Google event
  me.reportConversionGoal = function (i_product) {
    var product = typeof i_product == 'string' ? i_product : 'casino';
    
    var action = 'goal' + (is_stage ? '-stage' : '');
    try {
      if (conversion_data.type == 'optimizer') {
        if ('_gaq' in window && conversion_data.trackcode != '') {
          _gaq.push(['gwo._trackPageview', '/' + conversion_data.trackcode + '/goal']);
        }
      }
      else {
        if ('pageTracker' in window && '_trackEvent' in pageTracker && mkw != '') {
          var category = 'conversion/testid' + conversion_data.test_id + '_phase' + conversion_data.phase + '/' + conversion_data.combination;
          pageTracker._trackEvent(category, action, product);
        }
      }
    } catch (err) { }
  };
  
  addLoadEvent(me.init);
  
  return me;
})();

   var preload_iframe = (function (context) {
  var timeout = null;
  var placeholder = null;
  var THIS = context || {};
  
  THIS.check_data = function() {
    var res = true;
    res = res && 'iframe_tag' in THIS.data;
    res = res && 'placeholder_link_id' in THIS.data;
    return res;
  };
  
  THIS.init = function (i_data) {
    THIS.data = i_data;
    if (THIS.check_data()) {
      if ('addLoadEvent' in window) {
        addLoadEvent(THIS.create);
      }
      else {
        THIS.create();
      }
    }
  };
  
  THIS.create = function () {
    var placeholder_id = THIS.data.placeholder_id ? THIS.data.placeholder_id : 'iframe_placeholder';
    var placeholder = document.getElementById(placeholder_id);
    
    // if placeholder is not found, create a new one
    // hopefully, this is after page load so we'll have a body.
    if (!placeholder) {
      placeholder = document.createElement('div');
      placeholder.id = placeholder_id;
      try {
        if (document.body) {
          document.body.appendChild(placeholder);
        }
      }
      catch (e) {
        addLoadEvent(function () { document.body.appendChild(placeholder); });
      }
    }
    
    if (placeholder) {
      var img_wrapper = document.getElementById(THIS.data.placeholder_link_id);
      addEvent(img_wrapper, 'click', THIS.start);            
      THIS.timeout = setTimeout(THIS.start, THIS.data.timeout_interval);
    }
    THIS.placeholder = placeholder;
  };

  THIS.start = function () {
    if (THIS.timeout) {
      clearTimeout(THIS.timeout);
    }
    
    THIS.placeholder.innerHTML = THIS.data.iframe_tag;
  };

  return {
    'init' : THIS.init
  };
})();

   function fixPng() {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);

	if ((version >= 5.5) && (document.body.filters)) {
	  for(var i = 0; i < document.images.length; i++) {
	    var img = document.images[i];
	    var imgName = img.src.toUpperCase();
	    if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
	      var imgID = (img.id) ? "id='" + img.id + "' " : "";
	      var imgClass = (img.className) ? "class='" + img.className + "' " : "";
	      var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
	      var imgStyle = "display:inline-block;" + img.style.cssText;
	      if (img.align == "left") {
	        imgStyle = "float:left;" + imgStyle;
	      }
	      if (img.align == "right") {
	        imgStyle = "float:right;" + imgStyle;
	      }
	      if (img.parentElement.href) {
	        imgStyle = "cursor:hand;" + imgStyle;
	      }
	      var strNewHTML = "<span " + imgID + imgClass + imgTitle
	      + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	      + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	      + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
	      img.outerHTML = strNewHTML;
	      i = i - 1;
	    }
	  }
	}
}

   function OpenSafeCashier()
{	
	window.open("https://www.safe-cashier.com/" + rlLang  + "/Logon.aspx?sr=" + rlSerial + "&lang=" + rlLang + "&mkw=" + rlMkw, 'main','width=800,height=500,locationbar=yes');
}

   // This will output the segments found in sTestDataXML to a variable named 'segments'
var segments = (function (xml) {
  var res = [];
  
  if (typeof xml == 'string') {
    var segments_regex = /<segment>([^<]+)<\/segment>/gi;
    var matches = xml.match(segments_regex);
    for (var i in matches) {
      // for some reason, IE iterates not only on the array keys, but also on some other properties.
      // this makes sure we'll only look at results
      if (isNaN(parseInt(i))) {
        continue;
      }
      var match = matches[i];
      match = match.substring(9, match.length - 10);
      res.push(match);
    }
  }

  var res_str = res.sort().join('_');
  return (res_str == '' ? 'none' : res_str);
})(sTestDataXML);

