
//
// AdversitementCustom.js (Tue, 04 Mar 2008 14:15:34 +0100)
//

/*
Copyright (c) 2007, Adversitement BV  All rights reserved.
http://www.adversitement.nl
*/
/**
 * @fileoverview This file is used in combination with hbx.js from Visual Sciences.
 * It contains handy functions and fixes to HBX Analytics Code 
 * @author bartosz ( at ) adversitement.nl   
 * @version 1.8
 */  

// Create Adversitement namespace if it doesn't exists 
if(typeof(Adversitement) == 'undefined') {
  var Adversitement = {};
}


/**
 * Base functions used by all modules
 */
Adversitement.base = function() {
  //Private variables
  
  
  /**
   * Holds all functions that have to be executed just before Pageview request is constructed
   * @private   
   */     
  var onPrePVREvents = [];
  
  
  /**
   * Stores all event objects for use after a pageview gets send
   * @private
   */        
  var hbEvents = [];
  
  
  /**
   * Sets up all HBX Events interfaces with our own events
   * @private      
   */         
  var initEventInterfaces = function() {
    var oldOnPrePVR = function(r){};
    //if hbOnPrePVR already defined save its reference for later use
    if(typeof(_hbOnPrePVR) != 'undefined') {
       oldOnPrePVR = _hbOnPrePVR; 
    }
    // create global function _hbOnPrePVR
    _hbOnPrePVR = function(requestString) {
      oldOnPrePVR(requestString);
      storeEvents();
      for(var i=0; i<onPrePVREvents.length; i++) {
        onPrePVREvents[i](requestString);
      }
    }
  };
  
  
  /**
   * Store all events. Hbx code deletes these events after a pageview, but we may need them.
   * @private
   */        
  var storeEvents = function() {
    hbEvents = []; // delete all entries
    if(typeof(_hbE) != 'undefined') {
      for(var i=0; i<_hbE.length; i++) {
        hbEvents[i] = _hbE[i];
      }
    }
  };
  
  
  /**
   * Returns actual event object as defined with _hbEvent. Doesn't use our stored copies of event objects.
   * @param name Name of the event object
   * @returns HBX Event object or null if not found
   * @private   
   */   
  var getRealEventObject = function(name) {
    var ret = null;
    if(typeof(_hbE) != 'undefined') {
      for(var i=0; i<_hbE.length; i++) {
        if(typeof(_hbE[i]._N) != 'undefined' && _hbE[i]._N == name) {
          return _hbE[i];
        }
      }
    }
    return ret;
  };
  
  
  /**
   * Returns our stored copy of event object.
   * @param name Name of the event object
   * @returns HBX Event object or null if not found
   * @private   
   */   
  var getCopyEventObject = function(name) {
    var ret = null;
    for(var i=0; i<hbEvents.length; i++) {
      if(typeof(hbEvents[i]._N) != 'undefined' && hbEvents[i]._N == name) {
        return hbEvents[i];
      }
    }
    return ret;
  };


  //Public variables
  return /** @scope Adversitement.base */ {

    /**
     * Get parameter from URL. Not case sensitive.
     * @param parm Parameter name to be read from URL
     */              
    getParameter: function(parm) {
      var string = top.location.search.substring(1);
      var parameters = string.split("&");
      
      for(var i=0; i<parameters.length; i++) {
        var pair = parameters[i].split("=");
        if(pair.length > 0) {
          if(pair[0].toLowerCase() == parm) {
            return unescape(pair[1]);  
          }
        }
      }
      return '';
    },
    
    
    /**
     * Get parameter from Referrer URL. Not case sensitive.
     * @param parm Parameter name to be read from Referrer URL
     */              
    getReferrerParameter: function(parm) {
      var r = top.document.referrer;
      if(r.indexOf("?") != -1) {
        var string = r.substring(r.indexOf("?")).substring(1);
        var parameters = string.split("&");
        
        for(var i=0; i<parameters.length; i++) {
          var pair = parameters[i].split("=");
          if(pair.length > 0) {
            if(pair[0].toLowerCase() == parm) {
              return unescape(pair[1]);  
            }
          }
        }
      }
      return '';
    },
    
    
    /**
     * Returns referring domain
     */
    getReferringDomain: function() {
      if (document.referrer) {
        var d = document.referrer.match(/([^\/\/]+\.[^/.]+)\//)[1];
        if(d) {
          return d.replace(/www./i, '').toLowerCase();
        }
      }
      return '';
    },
             
    
    
    /**
     * Get parameter from hash string. Not case sensitive.
     * @param parm Parameter name to be read from Referrer URL
     */              
    getHashParameter: function(parm) {
      var h = top.location.hash;
      if(h.indexOf("#") != -1) {
        var string = h.substring(1);
        var parameters = string.split("&");
        
        for(var i=0; i<parameters.length; i++) {
          var pair = parameters[i].split("=");
          if(pair.length > 0) {
            if(pair[0].toLowerCase() == parm) {
              return unescape(pair[1]);
            }
          }
        }
      }
      return '';
    },
    
    
    /**
     * Additional campaign parameters
     */         
    campaignParameters: [],
    
    
    /**
     * Use Organic campaigns
     */
    useOrganicCampaigns: [],          
    
    
    /**
     * Gets campaign from URL or hbx.cmp
     * @returns Campaign Id or empty string if no campaign
     */              
    getCampaign: function() {
      var cmp = '';
      
      if(cmp == '') {
        if(typeof(_cmp) != 'undefined') {
          cmp = _cmp;
        }
      }
      
      if(cmp == '') {
        if(typeof(_dcmp) != 'undefined') {
          cmp = _dcmp;
        }
      }
      
      if(cmp == '') {
        if(typeof(_cmpn) != 'undefined' && _cmpn != '') {
          cmp = Adversitement.base.getParameter(_cmpn);
        }
      }
      
      if(cmp == '') {
        if(typeof(_dcmpn) != 'undefined' && _dcmpn != '') {
          cmp = Adversitement.base.getParameter(_dcmpn);
        }
      }
      
      if(cmp == '') {
        cmp = Adversitement.base.getParameter('cmp');
      }
      
      if(cmp == '') {
        cmp = Adversitement.base.getHashParameter('cmp');
      }
      
      if(cmp == '') {
        cmp = Adversitement.base.getParameter('ecmp');
      }
      
      if(cmp == '') {
        cmp = Adversitement.base.getParameter('dcmp');
      }
      
      if(cmp == '') {
        cmp = Adversitement.base.getParameter('hbx.cmp');
      }
      
      if(cmp == '') {
        cmp = Adversitement.base.getParameter('hbx.dcmp');
      }
      
      if(cmp == '') {
        if(typeof(Adversitement.base.campaignParameters) != 'undefined' && Adversitement.base.campaignParameters) {
          for(var i=0; i<Adversitement.base.campaignParameters.length; i++) {
            if(cmp == '') {
              cmp = Adversitement.base.getHashParameter(Adversitement.base.campaignParameters[i]);
            }
            if(cmp == '') {
              cmp = Adversitement.base.getParameter(Adversitement.base.campaignParameters[i]);
            }
          }  
        }
      }
      
      // organic campaigns
      if(cmp == '' && typeof(Adversitement.base.useOrganicCampaigns) != 'undefined' && Adversitement.base.useOrganicCampaigns && Adversitement.base.useOrganicCampaigns.length>0) {
        var d = Adversitement.base.getReferringDomain();
        for(var j=0; j<Adversitement.base.useOrganicCampaigns.length; j++) {
          if(d.indexOf(Adversitement.base.useOrganicCampaigns[j].toLowerCase()) != -1) {
            cmp = "Organic";
            break;
          }
        }
      }
      
      if(cmp != '') {
        cmp = Adversitement.base.trim(cmp);
      }
      
      return cmp;
    },
    
    
    /**
     * Get hbEvent object
     * @param name Name of the event to return     
     * @returns HBX Event object or null if not found
     */     
    getEventObject: function(name) {
      var ret = null;
      ret = getRealEventObject(name);
      if(ret == null) {
        ret = getCopyEventObject(name);
      }
      return ret;
    },
    
    
    /**
     * Get Order event object. May be a copy.
     * @returns Order Event Object     
     */         
    getOrderEventObject: function() {
      var order = Adversitement.base.getEventObject("order");
      if(!order) {
        order = Adversitement.base.getEventObject("ord");
      }
      return order;
    },
    
    
    /**
     * Get the actual Order event object and never a copy. Use this function if you want to set a order variable
     * @returns Order Event Object     
     */         
    getRealOrderEventObject: function() {
      var order = getRealEventObject("order");
      if(!order) {
        order = getRealEventObject("ord");
      }
      return order;
    },
    
    
    /**
     * Remove leading and trailing white space
     * @param str Source string
     * @returns Trimmed string
     */                   
    trim: function(str) {
      return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
    },
    
    
    /**
     * Return sum of comma delimited values
     * @returns Sum of comma delimited values
     */              
    sumOfAllValues: function(values) {
      var arr = values.split(',');
      var sum = 0;
      for(var i = 0; i<arr.length; i++) {
        var val = parseFloat(arr[i]);
        if(val) {
          sum += val;
        }
      }
      return sum;
    },
  
  
    /**
     * Replaces one string with another
     * @param str String where replacement takes place
     * @param pcFrom Source string
     * @param pcTo Destination String
     * @returns New string with replaced values
     */                              
    replaceAll: function(str, pcFrom, pcTo){
      var c = str;
      if(str) {
        var i = str.indexOf(pcFrom);
        while (i > -1){
          c = c.replace(pcFrom, pcTo);
          i = c.indexOf(pcFrom);
        }
      }
      return c;
    },
    
    
    /**
     * Sets Custom Metric to a value. Works also with Custom Metrics greater than 4.
     * @param customMetricNr Interger from 1 to 50 determines to which Custom Metric the value will be assigned
     * @param value Value to be assigned to a Custom Metric
     */                   
    setCustomMetric: function(customMetricNr, value) {
      var customMetricEvent = getRealEventObject("cv");
      if(customMetricNr <= 4) {
        //check if we are using events
        if(customMetricEvent) {
          if(typeof(customMetricEvent['c' + customMetricNr]) != 'undefined') {
            customMetricEvent['c' + customMetricNr] = value;
            return;
          }
        }
        if(customMetricNr == 1) {
          _hc1 = value;
        } else if(customMetricNr == 2) {
          _hc2 = value;
        } else if(customMetricNr == 3) {
          _hc3 = value;
        } else if(customMetricNr == 4) {
          _hc4 = value;
        }
      } else {
        //if event is not created, create one
        if(!customMetricEvent) {
          customMetricEvent = _hbEvent("cv");
        }
        customMetricEvent['c' + customMetricNr] = value;
      }
    },
    
    
    /**
     * Sets Order Level Commerce Custom Metric to a value. Works with Order Event only.
     * @param customMetricNr Interger from 1 to 10 determines to which Custom Metric the value will be assigned
     * @param value Value to be assigned to a Custom Metric
     */                   
    setOrderCustomMetric: function(customMetricNr, value) {
      var customMetricEvent = Adversitement.base.getRealOrderEventObject();
        //if event is not created, do nothing
        if(!customMetricEvent) {
          return
        }
        customMetricEvent['attr' + customMetricNr] = value;
    },
    
    
    /**
     * Determines if this is conversion page or order confirmation page
     * @returns true if either hbx.gp is not empty or this is order confirmation page
     */              
    isThisConversionPage: function() {
      // is this conversion page?
      if(typeof(_gp) != 'undefined' && _gp && _gp != "") {
        return true;
      }
      
      //is this order confirmation page?
      if(typeof(_oi) != 'undefined' && _oi && _oi != "" && _oi != "ORDER+ID") {
        return true;
      }
      
      //is this order confirmation page using events?
      var order = Adversitement.base.getOrderEventObject();
      if(order) {
        if(typeof(order.oi) != 'undefined' && order.oi && order.oi != "" && order.oi != "ORDER+ID") {
          return true;
        }
      }
      return false;
    },
    
    
    /**
     * Determines if this is order confirmation page
     * @returns true if this is oreder confirmation page
     */
    isThisOrderConfirmationPage: function() {
      //is this order confirmation page?
      if(typeof(_oi) != 'undefined' && _oi && _oi != "" && _oi != "ORDER+ID") {
        return true;
      }
      
      //is this order confirmation page using events?
      var order = Adversitement.base.getOrderEventObject();
      if(order) {
        if(typeof(order.oi) != 'undefined' && order.oi && order.oi != "" && order.oi != "ORDER+ID") {
          return true;
        }
      }
      return false;
    },
    
    
    /**
     * Gets value of HBX variable, either global or from pageview event.
     * @param eventVariableName Property name of the pageview Event(without underscore)
     * @param eventName Name of the event to use in case no global variable is defined. This variable can be an object(mostly used with Order events).
     * @returns Value of the HBX variable     
     */              
    getHbxVariable: function(eventVariableName, eventName) {
      if(!eventName) {
        eventName = 'pv';
      }
      if(typeof(window['_' + eventVariableName]) != 'undefined') {
        return window['_' + eventVariableName];
      } else {
        var event;
        if(typeof(eventName) == 'object') {
          event = eventName;
        } else {
          event = Adversitement.base.getEventObject(eventName);
        }
        if(event != null) {
          return event[eventVariableName];
        }
      }
      return null;
    },
    
    
    /**
     * Sets value of HBX variable both global and event.
     * @param eventVariableName Property name of the pageview Event(without underscore)
     * @param value Value to set     
     * @param eventName Name of the event to use in case no global variable is defined. This variable can be an object(mostly used with Order events).     
     */              
    setHbxVariable: function(eventVariableName, value, eventName) {
      if(!eventName) {
        eventName = 'pv';
      }
      
      window['_' + eventVariableName] = value;
      
      var event;
      if(typeof(eventName) == 'object') {
        event = eventName;
      } else {
        event = getRealEventObject(eventName);
      }
      // If event is not set do nothing
      if(event != null) {
        event[eventVariableName] = value;
        storeEvents();
      }
    },
    
    
    /**
     * Strip all illegal characters<br>
     * Usage: hbx.pn = _Adversitement.base.hbxStrip(hbx.pn); 
     * @param a Text to strip
     * @returns Text with illegal characters stripped
     */   
    hbxStrip: function(a) {
      a = a + '';
      a = a.split("|").join("");
      a = a.split("&").join("");
      a = a.split("'").join("");
      a = a.split("#").join("");
      a = a.split("$").join("");
      a = a.split("%").join("");
      a = a.split("^").join("");
      a = a.split("*").join("");
      a = a.split(":").join("");
      a = a.split("!").join("");
      a = a.split("<").join("");
      a = a.split(">").join("");
      a = a.split("~").join("");
      a = a.split(";").join("");
      a = a.split(" ").join("+");
      return a;    
    },
    
    
    /**
     * Add a function to be called in onPrePVR event
     * @param func function to be added
     */              
    addOnPrePVREvent: function(func) {
      onPrePVREvents.push(func);
    },
    
    
    /**
     * Version number
     * @returns version number
     */              
    version: function() {
      return 1.8;
    },
    
    
    /**
     * Init
     */         
    init: function() {
      initEventInterfaces();
    }
  };
}(); // create the actual object


/**
 * Create/Read/Delete cookies<br>
 */
Adversitement.cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    var domein = '';
    var path = '';
    var host = Adversitement.cookie.getHost();
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
      path = '; path=/';
      domein = '; domain='+host;
    }
    return (document.cookie = name + '=' + (value || '') + path + domein + expire);
  },
  
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  
  erase: function(name) {
    var cookie = Adversitement.cookie.get(name) || true;
    Adversitement.cookie.set(name, '', -1);
    return cookie;
  },
  
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Adversitement.cookie.set('_test', '1');
    return (Adversitement.cookie.erase('_test') === '1');
  },
  
  
  /**
   * Gets host suitable for inclusion in cookies<br>
   * www.google.com becomes .google.com
   * @returns domain without subdomains
   */                   
  getHost: function() {
    var newHost = "";
    try {
      var host = document.location.host;
      var values = host.split('.');
      if(values.length > 1) {
        newHost = '.' + values[values.length-2] + '.' + values[values.length-1];
      }
    } catch(e) {}
    return newHost;
  }
};



/**
 * Custom convenience functions and hbx interfaces
 */
Adversitement.custom = function() {
  //Private variables
  
  /**
   * Prefix to all cookie variables
   * @private
   */        
  var cookieName = '_Adver_custom_';
  
  
  /**
   * Save response to first campaign in a cookie to be read later
   * @private    
   */   
  var firstCampaignResponse = function() {
    var cmp = Adversitement.base.getCampaign();
    if(cmp != '') {
      var c = Adversitement.cookie.get(cookieName + 'FIRST_hbx.cmp');
			if(c == null) {
			  Adversitement.cookie.set(cookieName + 'FIRST_hbx.cmp', cmp, 30);
      }
		}
  };
  
  
  /**
   * If hbx.gp = 'first' set hbx.gp to a first campaign read from cookie, then delete cookie
   * @private   
   */   
  var firstCampaignConversion = function() {
    if(typeof(_gp) != 'undefined' && _gp && _gp.toLowerCase() == "first") { 
  		var _c = Adversitement.cookie.get(cookieName + 'FIRST_hbx.cmp');
  		_gp = (_c != null)?_c:'LAST';
  		Adversitement.cookie.erase(cookieName + 'FIRST_hbx.cmp');
  	}
  };

  
  //Public variables
  return /** @scope Adversitement.custom */ {
  
    /**
     * Adds hbx referrer from URL variable<br>
     * Used with Emails and Newsletters<br>
     * Usage: www.mypage.com/?adv_ref=http://email.mypage.com
     */           
    addReferrer: function() {
      var ref = Adversitement.base.trim(Adversitement.base.getParameter('adv_ref'));
      if(ref != '') {
        if(typeof(_hrf) == 'undefined' || _hrf == "") {
          if(ref.indexOf('http://') == -1 && ref.indexOf('https://') == -1) {
            ref = 'http://' + ref;
          }
          _hrf = ref;
        }
      }
    },
    
    
    /**
     * If hbx.gp = FIRST set hbx.gp to first campaign the user has responded to.
     */         
    firstCampaign: function() {
      firstCampaignResponse();
      firstCampaignConversion();
    },
    
    
    /**
     * If hbx.gp = LAST_NO_REFRESH prevent from repeat conversions within 5 minutes of last conversion
     */         
    lastNoRefresh: function() {
      if(typeof(_gp) != 'undefined' && _gp && _gp.toLowerCase() == "last_no_refresh") { 
    		var _c = Adversitement.cookie.get(cookieName + 'LAST_NO_REFRESH_hbx.gp');
    		if(_c == null) {
    		  _gp = 'LAST';
          Adversitement.cookie.set(cookieName + 'LAST_NO_REFRESH_hbx.gp', '1', 0.0035);
        } else {
          _gp = '';
        }
    	}
    },
    
    
    /**
     * Fix hbx.cu, hbx.ds, hbx.po variables that cause problems with some versions of hbx
     */     
    fixCommerceVariables: function() {
      if(typeof(_cu) != 'undefined' && _cu && _cu == "CUSTOMER+TYPE") {
        _cu = "";
      }
      if(typeof(_ds) != 'undefined' && _ds && _ds == "DISCOUNT") {
        _ds = "";
      }
      if(typeof(_po) != 'undefined' && _po && _po == "PROMOTION") {
        _po = "";
      }
      
      // if we are using order event
      var order = Adversitement.base.getOrderEventObject();
      if(order) {
        if(typeof(order.cu) != 'undefined' && order.cu && order.cu == "CUSTOMER+TYPE") {
          order.cu = "";
        }
        if(typeof(order.ds) != 'undefined' && order.ds && order.ds == "DISCOUNT") {
          order.ds = "";
        }
        if(typeof(order.po) != 'undefined' && order.po && order.po == "PROMOTION") {
          order.po = "";
        }
      }
    },
    
    
    /**
     * Get campaign from hash string
     */
    getCampaignFromHash: function() {
      if(typeof(_cmp) == 'undefined' || _cmp == '') {
        _cmp = Adversitement.base.getCampaign();
      }
    },         
    
    
    /*
      Static functions. These functions don't have to be called from an event but can be used at any time.
    */
    
    
    /**
     * Add to Cart Event
     * All lists comma delimited         
     * @param product Cart product
     * @param quantity Product quantity
     * @param price Product price
     * @param brand Product brand(optional)
     * @param category Product category(optional)
     * @param store Store(optional, defaults to 1)
     * @param pagename Page name(optional)
     * @param mlc Multi-Level Content(optionl)
     * @param commerce_id Commerce Account Id(optional)       
     */                                                     
    hbxAddCart: function(product, quantity, price, brand, category, store, pagename, mlc, commerce_id) {
      // strip illegal characters
      for(var i=0; i<arguments.length; i++) {
        arguments[i] = Adversitement.base.hbxStrip(arguments[i]);
      }

      var defPagename = Adversitement.base.getHbxVariable('pn');
      var defMlc = Adversitement.base.getHbxVariable('mlc');
      var defCommerceId = Adversitement.base.getHbxVariable('cacct', Adversitement.base.getOrderEventObject());
      
      _hbSet('epg', 'n'); //event gateway toggle
      _hbSet('cam', '0'); //cart add methodology: CAM = 0 indicates highwatermark, CAM = 1 indicates incremental
      _hbSet('pv', '0'); //product view flag: PV = 0 INDICATES cart add, PV = 1 Indicates product view
      _hbSet('abd_type', 'cart_add');
      _hbSet('product', product?product:'PRODUCT');
      _hbSet('quantity', quantity?quantity:'QUANTITY');
      _hbSet('brand', brand?brand:'BRAND');
      _hbSet('category', category?category:'CATEGORIES');
      _hbSet('price', price?price:'PRICE');
      _hbSet('store', store?store:'1');
      _hbSet('tz', 'ECT'); //customer time zone
      _hbSet('aid', commerce_id?commerce_id:defCommerceId?defCommerceId:'COMMERCE_ID');
      
      _hbPageView(pagename?pagename:defPagename?defPagename:"PUT+PAGE+NAME+HERE", mlc?mlc:defMlc?defMlc:"CONTENT+CATEGORY");
    },
    
    
    /**
     * Cart Checkout Event<br>
     * All lists comma delimited     
     * @param product List of products
     * @param quantity List of quantities
     * @param price List of prices
     * @param shippingtype Shipping type
     * @param shippingcost Shipping cost
     * @param store Store(optional, defaults to 1)
     * @param pagename Page name(optional)
     * @param mlc Multi-Level Content(optional)
     * @param commerce_id Commerce Account Id (optional)                        
     */              
    hbxCheckout: function(product, quantity, price, shippingtype, shippingcost, store, pagename, mlc, commerce_id) {
      // strip illegal characters
      for(var i=0; i<arguments.length; i++) {
        arguments[i] = Adversitement.base.hbxStrip(arguments[i]);
      }
      
      var defPagename = Adversitement.base.getHbxVariable('pn');
      var defMlc = Adversitement.base.getHbxVariable('mlc');
      var defCommerceId = Adversitement.base.getHbxVariable('cacct', Adversitement.base.getOrderEventObject());
      
      _hbSet('abd_type', 'checkout'); 
      _hbSet('tz', 'ECT'); //customer time zone
      _hbSet('product', product?product:'LIST_OF_PRODUCTS');
      _hbSet('quantity', quantity?quantity:'LIST_OF_QUANTITIES');
      _hbSet('price', price?price:'LIST_OF_PRICES');
      _hbSet('shippingtype', shippingtype?shippingtype:'SHIP_TYPE');
      _hbSet('shipping', shippingcost?shippingcost:'SHIP_COST');
      _hbSet('store', store?store:'1');
      _hbSet('aid', commerce_id?commerce_id:defCommerceId?defCommerceId:'COMMERCE_ID');
      
      _hbPageView(pagename?pagename:defPagename?defPagename:"PUT+PAGE+NAME+HERE", mlc?mlc:defMlc?defMlc:"CONTENT+CATEGORY");
    }
    
  };
}(); // create the actual object


/**
 * History Module.
 * Used by other modules to store multidimensional values in a cookie.
 */ 
Adversitement.history = function() {
  // private variables
  
  /**
   * Prefix to all cookie variables
   * @private
   */ 
  var cookieName = '_Adver_history_';
  
  
  //Public variables
  return /** @scope Adversitement.history */ {
  
    add: function() {
      var historyId = arguments[0];
      for(var i=1; i<arguments.length; i++) {
        var old = Adversitement.cookie.get(cookieName + historyId + '_' + i);
        if(old && old != '') {
          old = old + '~';
        } else {
          old = '';
        }
        if(!Adversitement.history.exists(historyId, arguments[i], i)) {
          Adversitement.cookie.set(cookieName + historyId + '_' + i, old + arguments[i], 30);
        }
      }
    },
    
    clear: function(historyId) {
      for(var i=1; i<100; i++) {
        var c = Adversitement.cookie.get(cookieName + historyId + '_' + i);
        if(c && c != '') {
          Adversitement.cookie.erase(cookieName + historyId + '_' + i);
        } else {
          return;
        }
      }
    },
    
    read: function(historyId) {
      var arr = [];
      for(var i=1; i<100; i++) {
        var c = Adversitement.cookie.get(cookieName + historyId + '_' + i);
        if(c && c != '') {
          arr.push(c);
        } else {
          return arr;
        }
      }
      return arr;
    },
    
    exists: function(historyId, value, dimension) {
      var c = Adversitement.cookie.get(cookieName + historyId + '_' + dimension);
      if(c && c != '') {
        values = c.split('~');
        for(var j=0; j<values.length; j++) {
          if(values[j]==value) {
            return true;
          }
        }
      }
      return false;
    },
    
    getLastValue: function(historyId, dimension) {
      var ret = "";
      if(!dimension) {
        dimension = 0;
      }
      var h = Adversitement.history.read(historyId);
      if(h && h.length > 0) {
        var values = h[dimension];
        if(values && values != "") {
          var valuesArray = values.split('~');
          ret = valuesArray[valuesArray.length - 1];
        }
      }
      return ret;
    }
  };
}(); // create the actual object


/**
 * Track all campaigns that a visitor has responded to and save it in a custom metric<br>
 * Works only on tagged campaigns and tagged conversions
 */
Adversitement.campaignHistory = function() {
  // private variables
  
  /**
   * Adds current campaign if avaible to campaign history
   * @private   
   */         
  var addCampaign = function() {
    var cmp = Adversitement.base.getCampaign();
    if(cmp != '') {
      Adversitement.history.add('campaign', cmp.toLowerCase());
    } else {
      //Direct visits
      if(Adversitement.campaignHistory.useDirect && top.document.referrer == "") {
        Adversitement.history.add('campaign', "Direct");
      }
    }
  };
  
  /**
   * Returns all campaigns as a string, ready to be inserted in a custom metric
   * @param commerce If true returns first dimension only   
   * @private   
   */         
  var getCampaignsCustomMetric = function(commerce) {
    var campaigns = Adversitement.history.read('campaign');
    if(campaigns.length > 0) {
      var dimension1 = campaigns[0];
      var dimension2 = '';
      
      // If this is order confirmation page use Price instead of Conversion Value
      if(Adversitement.base.isThisOrderConfirmationPage()) {
        if(typeof(_pc) != 'undefined' && _pc && _pc != "" && _pc != "PRICE") {
          dimension2 = _pc;
        }
        var orderEvent = Adversitement.base.getOrderEventObject();
        if(orderEvent && typeof(orderEvent.pc) != 'undefined' && orderEvent.pc && orderEvent.pc != "" && orderEvent.pc != "PRICE") {
          dimension2 = orderEvent.pc;
        }
        if(dimension2 && dimension2.length>0) {
          // we want one price only, so get sum of all the prices
          dimension2 = Adversitement.base.sumOfAllValues(dimension2);
        } else {
          dimension2 = '';
        }
      } else {
        if(typeof(_hcv) != 'undefined') {
          dimension2 = _hcv;
        }
      }
      if(dimension1 != '') {
        Adversitement.history.clear('campaign');
        if((commerce && commerce == true) || dimension2 == '') {
          return dimension1;
        }
        if(dimension2) {
          dimension2 = Math.round(parseFloat(dimension2)*100);
        }
        return dimension1 + '|' + dimension2;
      } else {
        return '';
      }
    } else {
      return '';
    }
  };
  
  //Public variables
  return /** @scope Adversitement.campaignHistory */ {
    
    /**
     * Determines if direct visits will be added to campaign history
     */         
    useDirect: false,
    
    /**
     * Places campaigns in history.
     * If it is conversion page or order confiramtion page sets custom metric to a value from campaign history
     * @param customMetricNr Integer from 1 to 50 indicating where to place the results
     * @param commerce If true sets Order Level Commerce Custom Metrics instead of standard Custom Metrics          
     */         
    init: function(customMetricNr, commerce) {
      addCampaign();
      if(Adversitement.base.isThisConversionPage()) {
        if(commerce && commerce == true) {
          Adversitement.base.setOrderCustomMetric(customMetricNr, getCampaignsCustomMetric(true));
        } else {
          Adversitement.base.setCustomMetric(customMetricNr, getCampaignsCustomMetric());
        }
      }
    }
  };
}(); // create the actual object


/**
 * Track all typed internal keywords and save them in a custom metric on conversion<br>  
 */
Adversitement.internalSearchHistory = function() {
  // private variables
  
  /**
   * Adds current keyword if avaible to search history
   * @private   
   */ 
  var addKeywords = function() {
    var search = Adversitement.base.getEventObject("search");
    if(search) {
      var keyword = Adversitement.base.trim(search.keywords);
      keyword = Adversitement.base.hbxStrip(keyword);
      var lastKeyword = Adversitement.history.getLastValue("search");
      if(search.results && search.results != "0" && keyword != "" && keyword != lastKeyword) {
        Adversitement.history.add("search", keyword);
      }
    }
  };
  
  
  /**
   * Returns all keywords as a string, ready to be inserted in a custom metric
   * @param commerce If true returns first dimension only   
   * @private   
   */
  var getKeywordsCustomMetric = function(commerce) {
    var ret = "";
    var keywords = Adversitement.history.read("search");
    if(keywords.length > 0) {
      //we are only interested in first dimension
      keywords = keywords[0];    
      
      if(keywords != "") {
        var dimension1 = keywords;
        var dimension2 = Adversitement.history.getLastValue("search");
        ret = dimension1 + '|' + dimension2;
        if(commerce && commerce == true) {
          ret = dimension1;
        }
        Adversitement.history.clear("search");
      }
    }
    return ret;
  };
  
  //Public variables
  return /** @scope Adversitement.internalSearchHistory */ {
  
    /**
     * Places internal search keywords in history.
     * If it is conversion page or order confiramtion page sets custom metric to a value from internal search history
     * @param customMetricNr Integer from 1 to 50 indicating where to place the results
     * @param commerce If true sets Order Level Commerce Custom Metrics instead of standard Custom Metrics     
     */ 
    init: function(customMetricNr, commerce) {
      addKeywords();
      if(Adversitement.base.isThisConversionPage()) {
        if(commerce && commerce == true) {
          Adversitement.base.setOrderCustomMetric(customMetricNr, getKeywordsCustomMetric(true));
        } else {
          Adversitement.base.setCustomMetric(customMetricNr, getKeywordsCustomMetric());
        }
      }
    }
  };
}(); // create the actual object


/**
 * Track last campaign attribute and save it as conversion attribute  
 */
Adversitement.campaignAttributeHistory = function() {
  // private variables
  
  
  var attributeNames = [];
  
  
  /**
   * Adds campaign response attribute if avaible to history
   * @private   
   */ 
  var addAttribute = function() {
    var attr = '';
    attr = Adversitement.base.getParameter('hbx.hra');
    if(attr == '') {
      if(typeof(_hra) != 'undefined' && _hra != '') {
        attr = _hra;
      }
    }
    if(attr == '') {
      var hqsp = Adversitement.base.getHbxVariable('hqsp');
      if(hqsp != null && hqsp != '') {
        attr = Adversitement.base.getParameter(hqsp);  
      }
    }
    
    if(attr == '') {
      var hqsr = Adversitement.base.getHbxVariable('hqsr');
      if(hqsr != null && hqsr != '') {
        attr = Adversitement.base.getReferrerParameter(hqsr);  
      }
    }
    if(attr == '') {
      for(var i=0; i<attributeNames.length; i++) {
        attr = Adversitement.base.getParameter(attributeNames[i]);
        if(attr != '') {
          break;
        }
      }
    }
    if(attr != '') {
      //we only want last campaign attribute
      Adversitement.history.clear("cmp_attribute");
      
      Adversitement.history.add("cmp_attribute", attr);
    } else {
      var cmp = Adversitement.base.getCampaign();
      if(cmp != '') {
        Adversitement.history.clear("cmp_attribute");
      }
    }
  };
  
  
  /**
   * Returns Campaign Attribute stored in history   
   * @private   
   */
  var getAttribute = function() {
    var ret = "";
    var attr = Adversitement.history.read("cmp_attribute");
    if(attr.length > 0) {
      //we are only interested in first dimension
      attr = attr[0];    
      
      if(attr != '') {
        ret = attr;
        Adversitement.history.clear("cmp_attribute");
      }
    }
    return ret;
  };
  
  //Public variables
  return /** @scope Adversitement.campaignAttributeHistory */ {
  
    /**
     * Places last campaign attribute in history.
     * If it is conversion page or order confiramtion page sets conversion attribute to a value from attributes history
     * @param attrs Array of attribute names to look for in a URL     
     */ 
    init: function(attrs) {
      if(typeof(attrs) != 'undefined' && attrs.length > 0) {
        attributeNames = attrs;
      }
      addAttribute();
      if(Adversitement.base.isThisConversionPage()) {
        var conversionAttribute =  Adversitement.base.getHbxVariable('hcn');
        if(conversionAttribute !== null && conversionAttribute == "") {
          Adversitement.base.setHbxVariable('hcn', getAttribute());
        }
      }
    }
  };
}(); // create the actual object


// Call init function to set up hooks to event interfaces
Adversitement.base.init();

// Everything below this line is optional


//Adversitement.base.campaignParameters = ['cmpid'];
//Adversitement.base.useOrganicCampaigns = ['google.', 'yahoo.', 'live.com', 'ilse.nl'];
//Adversitement.campaignHistory.useDirect = true;

// functions to be executed just before request construction. You can delete these functions if you don't need them.
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.addReferrer);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.fixCommerceVariables);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.firstCampaign);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.lastNoRefresh);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.getCampaignFromHash);


//Belvilla
//Track google keywords and related landing pages
Adversitement.base.addOnPrePVREvent(function(){
  if(document.referrer.indexOf('google.')!=-1) {
    var q = Adversitement.base.getReferrerParameter('q');
    q = Adversitement.base.hbxStrip(q);
    var url = document.location.href.replace('http://', '').replace('https://', '');
    if(q) {
      Adversitement.base.setCustomMetric(2, q + '|' + url);
    }
  }  
});

// Uncomment lines below to track history.
// Don't forget to set parameter to a Custom Metric that you want to use

//Adversitement.base.addOnPrePVREvent(function() {Adversitement.campaignHistory.init(1, true)}); // uses commerce custom metrics
//Adversitement.base.addOnPrePVREvent(function() {Adversitement.internalSearchHistory.init(2)});
//Adversitement.base.addOnPrePVREvent(function() {Adversitement.campaignAttributeHistory.init(['banner', 'attr'])});

//
// array.js (Tue, 20 Nov 2007 10:48:29 +0100)
//

/**
 * Array functions
 */

//
// Add one or more arrays, and return the new array. No array is modified.
// Arguments:
//    a - The array that has to be joined with this array
//
if ( typeof Array.prototype.concat === 'undefined' ) {
	Array.prototype.concat = function(a) {
		for(var i = 0, b = this.copy(); i < a.length; i++) {
			b[b.length] = a[i];
		}
		return b;
	};
}

//
// Copy all elements to a new array, by reference if possible, or by value.
//
if ( typeof Array.prototype.copy === 'undefined' ) {
	Array.prototype.copy = function() {
		var a = [], i = this.length;
		while(i--) {
			a[i] = (typeof this[i].copy !== 'undefined') ? this[i].copy() : this[i];
		}
		return a;
	};
}

//
// Remove and return the last element of an array.
//
if ( typeof Array.prototype.pop === 'undefined' ) {
	Array.prototype.pop = function() {
		var b = this[this.length-1];
		this.length--;
		return b;
	};
}

//
// Add one or more elements to the end of an array, return the new length.
//
if ( typeof Array.prototype.push === 'undefined' ) {
	Array.prototype.push == function() {
		for(var i = 0, b = this.length, a = arguments, l = a.length; i < l; i++) {
			this[b + i] = a[i];
		}
		return this.length;
	};
}

//
// Remove and return the first element.
//
if ( typeof Array.prototype.shift === 'undefined' ) {
	Array.prototype.shift = function() {
		for(var i = 0, b = this[0], l = this.length - 1; i < l; i++) {
			this[i] = this[i + 1];
		}
		this.length--;
		return b;
	};
}

//
// Copy and return several elements. The original array is not modified.
//
if ( typeof Array.prototype.slice === 'undefined' ) {
	Array.prototype.slice = function(a, c) {
		var i, l = this.length, r = [];
		if( !c ) { c = l; }
		if( c < 0 ) { c = l + c; }
		if( a < 0 ) { a = l - a; }
		if( c < a ) { i = a; a = c; c = i; }
		for( i = 0; i < c - a; i++ ) { r[i] = this[a + i]; }
		return r;
	};
}

//
// Remove or replace several elements and return any deleted elements.
//
if ( typeof Array.prototype.splice === 'undefined' ) {
	Array.prototype.splice = function(a, c) {
		var i = 0, e = arguments, d = this.copy(), f = a, l = this.length;
		if( !c ) { c = l - a; }
		for( i; i < e.length - 2; i++ ) { this[a + i] = e[i + 2]; }
		for( a; a < l - c; a++ ) { this[a + e.length - 2] = d[a - c]; }
		this.length -= c - e.length + 2;
		return d.slice(f, f + c);
	};
}

//
// Add an element to the beginning of an array, return the new length.
//
if ( typeof Array.prototype.unshift === 'undefined' ) {
	Array.prototype.unshift = function() {
		this.reverse();
		var a = arguments, i = a.length;
		while(i--) { this.push(a[i]); }
		this.reverse();
		return this.length;
	};
}

//
// Return index of the first element that matches value.
// Arguments:
//    v - value
//    b - search from this element forward
//    s - search strict
Array.prototype.indexOf = function( v, b, s ) {
	for( var i = +b || 0, l = this.length; i < l; i++ ) {
		if( this[i]===v || s && this[i]==v ) { return i; }
	}
	return -1;
};

//
// Return index of the last element that matches value.
// Arguments:
//    v - value
//    b - search from this element backward
//    s - search strict
Array.prototype.lastIndexOf = function( v, b, s ) {
	b = +b || 0;
	var i = this.length;
	while(i-->b) {
		if( this[i]===v || s && this[i]==v ) { return i; }
	}
	return -1;
};

//
// Return an array where duplicate elements have been removed.
//
Array.prototype.unique = function( b ) {
	var a = [], i, l = this.length;
	for( i=0; i<l; i++ ) {
		if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
	}
	return a;
};

//
// dom.js (Tue, 20 Nov 2007 10:48:29 +0100)
//

/**
 * DOM functions
 */

function isIgnorable(node) {
	return (node.nodeType == 8 || (node.nodeType == 3 && !/[^\t\n\r ]/.test(node.data)));
}

function nodeBefore(sibling) {
	if ( sibling ) {
		while((sibling = sibling.previousSibling)) {
			if ( !isIgnorable(sibling) ) return sibling;
		}
	}
	
	return null;
}

function nodeAfter(sibling) {
	if ( sibling ) {
		while((sibling = sibling.nextSibling)) {
			if ( !isIgnorable(sibling) ) return sibling;
		}
	}
	
	return null;
}

function firstChild(parent) {
	if ( parent && parent.nodeType == 1 ) {
		var result = parent.firstChild;
		do {
			if ( !isIgnorable(result) ) return result;
		} while((result = result.nextSibling));
	}
}

function lastChild(parent) {
	if ( parent && parent.nodeType == 1 ) {
		var result = parent.lastChild;
		do {
			if ( !isIgnorable(result) ) return result;
		} while((result = result.previousSibling));
	}
}

//
// Class functions
function getElementsByClassName(className, tagName) {
	if ( !tagName ) tagName = '*';
	var tagNameRegex = new RegExp('(^|\\s)' + className + '(\\s|$)');
	var el = document.getElementsByTagName(tagName), i = el.length, e, result = [];
	
	while(i--) {
		e = el[i];
		if ( e.className && tagNameRegex.test(e.className)) result.push(e);
	}
	
	return result;
}

function getClassList(el) {
	if ( el.className ) return el.className.split(/\s+/);
	return [];
}

function setClassList(el, classes) {
	el.className = classes.join(' ');
}

function hasClass(el, className) {
	var classes = getClassList(el);
	return classes.indexOf(className) > -1;
}

function addClass(el, className) {
	var classes = getClassList(el);
	if ( classes.indexOf(className) == -1 ) {
		classes[classes.length] = className;
	}
	setClassList(el, classes);
}

function removeClass(el, className) {
	var classes = getClassList(el), index;
	if ((index = classes.indexOf(className)) > -1) {
		delete classes[index];
	}
	setClassList(el, classes);
}

function replaceClass(el, oldclass, newclass) {
	var classes = getClassList(el), index;
	if ((index = classes.indexOf(oldclass)) > -1 && classes.indexOf(newclass) == -1)
	{
		classes[index] = newclass;
	}
	setClassList(el, classes);
}

//
// AdversitementCustom_min.js (Tue, 04 Mar 2008 14:17:34 +0100)
//

if(typeof (Adversitement)=="undefined"){var Adversitement={}}Adversitement.base=function(){var F=[];var E=[];var B=function(){var G=function(H){};if(typeof (_hbOnPrePVR)!="undefined"){G=_hbOnPrePVR}_hbOnPrePVR=function(H){G(H);C();for(var I=0;I<F.length;I++){F[I](H)}}};var C=function(){E=[];if(typeof (_hbE)!="undefined"){for(var G=0;G<_hbE.length;G++){E[G]=_hbE[G]}}};var D=function(H){var G=null;if(typeof (_hbE)!="undefined"){for(var I=0;I<_hbE.length;I++){if(typeof (_hbE[I]._N)!="undefined"&&_hbE[I]._N==H){return _hbE[I]}}}return G};var A=function(H){var G=null;for(var I=0;I<E.length;I++){if(typeof (E[I]._N)!="undefined"&&E[I]._N==H){return E[I]}}return G};return{getParameter:function(K){var G=top.location.search.substring(1);var I=G.split("&");for(var H=0;H<I.length;H++){var J=I[H].split("=");if(J.length>0){if(J[0].toLowerCase()==K){return unescape(J[1])}}}return""},getReferrerParameter:function(L){var J=top.document.referrer;if(J.indexOf("?")!=-1){var G=J.substring(J.indexOf("?")).substring(1);var I=G.split("&");for(var H=0;H<I.length;H++){var K=I[H].split("=");if(K.length>0){if(K[0].toLowerCase()==L){return unescape(K[1])}}}}return""},getReferringDomain:function(){if(document.referrer){var G=document.referrer.match(/([^\/\/]+\.[^/.]+)\//)[1];if(G){return G.replace(/www./i,"").toLowerCase()}}return""},getHashParameter:function(L){var I=top.location.hash;if(I.indexOf("#")!=-1){var G=I.substring(1);var J=G.split("&");for(var H=0;H<J.length;H++){var K=J[H].split("=");if(K.length>0){if(K[0].toLowerCase()==L){return unescape(K[1])}}}}return""},campaignParameters:[],useOrganicCampaigns:[],getCampaign:function(){var I="";if(I==""){if(typeof (_cmp)!="undefined"){I=_cmp}}if(I==""){if(typeof (_dcmp)!="undefined"){I=_dcmp}}if(I==""){if(typeof (_cmpn)!="undefined"&&_cmpn!=""){I=Adversitement.base.getParameter(_cmpn)}}if(I==""){if(typeof (_dcmpn)!="undefined"&&_dcmpn!=""){I=Adversitement.base.getParameter(_dcmpn)}}if(I==""){I=Adversitement.base.getParameter("cmp")}if(I==""){I=Adversitement.base.getHashParameter("cmp")}if(I==""){I=Adversitement.base.getParameter("ecmp")}if(I==""){I=Adversitement.base.getParameter("dcmp")}if(I==""){I=Adversitement.base.getParameter("hbx.cmp")}if(I==""){I=Adversitement.base.getParameter("hbx.dcmp")}if(I==""){if(typeof (Adversitement.base.campaignParameters)!="undefined"&&Adversitement.base.campaignParameters){for(var H=0;H<Adversitement.base.campaignParameters.length;H++){if(I==""){I=Adversitement.base.getHashParameter(Adversitement.base.campaignParameters[H])}if(I==""){I=Adversitement.base.getParameter(Adversitement.base.campaignParameters[H])}}}}if(I==""&&typeof (Adversitement.base.useOrganicCampaigns)!="undefined"&&Adversitement.base.useOrganicCampaigns&&Adversitement.base.useOrganicCampaigns.length>0){var J=Adversitement.base.getReferringDomain();for(var G=0;G<Adversitement.base.useOrganicCampaigns.length;G++){if(J.indexOf(Adversitement.base.useOrganicCampaigns[G].toLowerCase())!=-1){I="Organic";break}}}if(I!=""){I=Adversitement.base.trim(I)}return I},getEventObject:function(H){var G=null;G=D(H);if(G==null){G=A(H)}return G},getOrderEventObject:function(){var G=Adversitement.base.getEventObject("order");if(!G){G=Adversitement.base.getEventObject("ord")}return G},getRealOrderEventObject:function(){var G=D("order");if(!G){G=D("ord")}return G},trim:function(G){return G.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1")},sumOfAllValues:function(H){var G=H.split(",");var J=0;for(var I=0;I<G.length;I++){var K=parseFloat(G[I]);if(K){J+=K}}return J},replaceAll:function(J,I,H){var K=J;if(J){var G=J.indexOf(I);while(G>-1){K=K.replace(I,H);G=K.indexOf(I)}}return K},setCustomMetric:function(G,H){var I=D("cv");if(G<=4){if(I){if(typeof (I["c"+G])!="undefined"){I["c"+G]=H;return }}if(G==1){_hc1=H}else{if(G==2){_hc2=H}else{if(G==3){_hc3=H}else{if(G==4){_hc4=H}}}}}else{if(!I){I=_hbEvent("cv")}I["c"+G]=H}},setOrderCustomMetric:function(G,H){var I=Adversitement.base.getRealOrderEventObject();if(!I){return }I["attr"+G]=H},isThisConversionPage:function(){if(typeof (_gp)!="undefined"&&_gp&&_gp!=""){return true}if(typeof (_oi)!="undefined"&&_oi&&_oi!=""&&_oi!="ORDER+ID"){return true}var G=Adversitement.base.getOrderEventObject();if(G){if(typeof (G.oi)!="undefined"&&G.oi&&G.oi!=""&&G.oi!="ORDER+ID"){return true}}return false},isThisOrderConfirmationPage:function(){if(typeof (_oi)!="undefined"&&_oi&&_oi!=""&&_oi!="ORDER+ID"){return true}var G=Adversitement.base.getOrderEventObject();if(G){if(typeof (G.oi)!="undefined"&&G.oi&&G.oi!=""&&G.oi!="ORDER+ID"){return true}}return false},getHbxVariable:function(H,G){if(!G){G="pv"}if(typeof (window["_"+H])!="undefined"){return window["_"+H]}else{var I;if(typeof (G)=="object"){I=G}else{I=Adversitement.base.getEventObject(G)}if(I!=null){return I[H]}}return null},setHbxVariable:function(H,J,G){if(!G){G="pv"}window["_"+H]=J;var I;if(typeof (G)=="object"){I=G}else{I=D(G)}if(I!=null){I[H]=J;C()}},hbxStrip:function(G){G=G+"";G=G.split("|").join("");G=G.split("&").join("");G=G.split("'").join("");G=G.split("#").join("");G=G.split("$").join("");G=G.split("%").join("");G=G.split("^").join("");G=G.split("*").join("");G=G.split(":").join("");G=G.split("!").join("");G=G.split("<").join("");G=G.split(">").join("");G=G.split("~").join("");G=G.split(";").join("");G=G.split(" ").join("+");return G},addOnPrePVREvent:function(G){F.push(G)},version:function(){return 1.8},init:function(){B()}}}();Adversitement.cookie={set:function(D,F,C){var B="";var A="";var G="";var E=Adversitement.cookie.getHost();if(C!=undefined){var H=new Date();H.setTime(H.getTime()+(86400000*parseFloat(C)));B="; expires="+H.toGMTString();G="; path=/";A="; domain="+E}return(document.cookie=D+"="+(F||"")+G+A+B)},get:function(A){var B=document.cookie.match(new RegExp("(^|;)\\s*"+escape(A)+"=([^;\\s]*)"));return(B?unescape(B[2]):null)},erase:function(A){var B=Adversitement.cookie.get(A)||true;Adversitement.cookie.set(A,"",-1);return B},accept:function(){if(typeof navigator.cookieEnabled=="boolean"){return navigator.cookieEnabled}Adversitement.cookie.set("_test","1");return(Adversitement.cookie.erase("_test")==="1")},getHost:function(){var B="";try{var C=document.location.host;var A=C.split(".");if(A.length>1){B="."+A[A.length-2]+"."+A[A.length-1]}}catch(D){}return B}};Adversitement.custom=function(){var C="_Adver_custom_";var A=function(){var D=Adversitement.base.getCampaign();if(D!=""){var E=Adversitement.cookie.get(C+"FIRST_hbx.cmp");if(E==null){Adversitement.cookie.set(C+"FIRST_hbx.cmp",D,30)}}};var B=function(){if(typeof (_gp)!="undefined"&&_gp&&_gp.toLowerCase()=="first"){var D=Adversitement.cookie.get(C+"FIRST_hbx.cmp");_gp=(D!=null)?D:"LAST";Adversitement.cookie.erase(C+"FIRST_hbx.cmp")}};return{addReferrer:function(){var D=Adversitement.base.trim(Adversitement.base.getParameter("adv_ref"));if(D!=""){if(typeof (_hrf)=="undefined"||_hrf==""){if(D.indexOf("http://")==-1&&D.indexOf("https://")==-1){D="http://"+D}_hrf=D}}},firstCampaign:function(){A();B()},lastNoRefresh:function(){if(typeof (_gp)!="undefined"&&_gp&&_gp.toLowerCase()=="last_no_refresh"){var D=Adversitement.cookie.get(C+"LAST_NO_REFRESH_hbx.gp");if(D==null){_gp="LAST";Adversitement.cookie.set(C+"LAST_NO_REFRESH_hbx.gp","1",0.0035)}else{_gp=""}}},fixCommerceVariables:function(){if(typeof (_cu)!="undefined"&&_cu&&_cu=="CUSTOMER+TYPE"){_cu=""}if(typeof (_ds)!="undefined"&&_ds&&_ds=="DISCOUNT"){_ds=""}if(typeof (_po)!="undefined"&&_po&&_po=="PROMOTION"){_po=""}var D=Adversitement.base.getOrderEventObject();if(D){if(typeof (D.cu)!="undefined"&&D.cu&&D.cu=="CUSTOMER+TYPE"){D.cu=""}if(typeof (D.ds)!="undefined"&&D.ds&&D.ds=="DISCOUNT"){D.ds=""}if(typeof (D.po)!="undefined"&&D.po&&D.po=="PROMOTION"){D.po=""}}},getCampaignFromHash:function(){if(typeof (_cmp)=="undefined"||_cmp==""){_cmp=Adversitement.base.getCampaign()}},hbxAddCart:function(O,G,J,F,D,N,I,M,P){for(var H=0;H<arguments.length;H++){arguments[H]=Adversitement.base.hbxStrip(arguments[H])}var L=Adversitement.base.getHbxVariable("pn");var E=Adversitement.base.getHbxVariable("mlc");var K=Adversitement.base.getHbxVariable("cacct",Adversitement.base.getOrderEventObject());_hbSet("epg","n");_hbSet("cam","0");_hbSet("pv","0");_hbSet("abd_type","cart_add");_hbSet("product",O?O:"PRODUCT");_hbSet("quantity",G?G:"QUANTITY");_hbSet("brand",F?F:"BRAND");_hbSet("category",D?D:"CATEGORIES");_hbSet("price",J?J:"PRICE");_hbSet("store",N?N:"1");_hbSet("tz","ECT");_hbSet("aid",P?P:K?K:"COMMERCE_ID");_hbPageView(I?I:L?L:"PUT+PAGE+NAME+HERE",M?M:E?E:"CONTENT+CATEGORY")},hbxCheckout:function(N,E,I,G,P,M,H,L,O){for(var F=0;F<arguments.length;F++){arguments[F]=Adversitement.base.hbxStrip(arguments[F])}var K=Adversitement.base.getHbxVariable("pn");var D=Adversitement.base.getHbxVariable("mlc");var J=Adversitement.base.getHbxVariable("cacct",Adversitement.base.getOrderEventObject());_hbSet("abd_type","checkout");_hbSet("tz","ECT");_hbSet("product",N?N:"LIST_OF_PRODUCTS");_hbSet("quantity",E?E:"LIST_OF_QUANTITIES");_hbSet("price",I?I:"LIST_OF_PRICES");_hbSet("shippingtype",G?G:"SHIP_TYPE");_hbSet("shipping",P?P:"SHIP_COST");_hbSet("store",M?M:"1");_hbSet("aid",O?O:J?J:"COMMERCE_ID");_hbPageView(H?H:K?K:"PUT+PAGE+NAME+HERE",L?L:D?D:"CONTENT+CATEGORY")}}}();Adversitement.history=function(){var A="_Adver_history_";return{add:function(){var D=arguments[0];for(var C=1;C<arguments.length;C++){var B=Adversitement.cookie.get(A+D+"_"+C);if(B&&B!=""){B=B+"~"}else{B=""}if(!Adversitement.history.exists(D,arguments[C],C)){Adversitement.cookie.set(A+D+"_"+C,B+arguments[C],30)}}},clear:function(C){for(var B=1;B<100;B++){var D=Adversitement.cookie.get(A+C+"_"+B);if(D&&D!=""){Adversitement.cookie.erase(A+C+"_"+B)}else{return }}},read:function(D){var B=[];for(var C=1;C<100;C++){var E=Adversitement.cookie.get(A+D+"_"+C);if(E&&E!=""){B.push(E)}else{return B}}return B},exists:function(D,C,E){var F=Adversitement.cookie.get(A+D+"_"+E);if(F&&F!=""){values=F.split("~");for(var B=0;B<values.length;B++){if(values[B]==C){return true}}}return false},getLastValue:function(F,G){var D="";if(!G){G=0}var E=Adversitement.history.read(F);if(E&&E.length>0){var B=E[G];if(B&&B!=""){var C=B.split("~");D=C[C.length-1]}}return D}}}();Adversitement.campaignHistory=function(){var A=function(){var C=Adversitement.base.getCampaign();if(C!=""){Adversitement.history.add("campaign",C.toLowerCase())}else{if(Adversitement.campaignHistory.useDirect&&top.document.referrer==""){Adversitement.history.add("campaign","Direct")}}};var B=function(E){var G=Adversitement.history.read("campaign");if(G.length>0){var D=G[0];var C="";if(Adversitement.base.isThisOrderConfirmationPage()){if(typeof (_pc)!="undefined"&&_pc&&_pc!=""&&_pc!="PRICE"){C=_pc}var F=Adversitement.base.getOrderEventObject();if(F&&typeof (F.pc)!="undefined"&&F.pc&&F.pc!=""&&F.pc!="PRICE"){C=F.pc}if(C&&C.length>0){C=Adversitement.base.sumOfAllValues(C)}else{C=""}}else{if(typeof (_hcv)!="undefined"){C=_hcv}}if(D!=""){Adversitement.history.clear("campaign");if((E&&E==true)||C==""){return D}if(C){C=Math.round(parseFloat(C)*100)}return D+"|"+C}else{return""}}else{return""}};return{useDirect:false,init:function(C,D){A();if(Adversitement.base.isThisConversionPage()){if(D&&D==true){Adversitement.base.setOrderCustomMetric(C,B(true))}else{Adversitement.base.setCustomMetric(C,B())}}}}}();Adversitement.internalSearchHistory=function(){var B=function(){var D=Adversitement.base.getEventObject("search");if(D){var C=Adversitement.base.trim(D.keywords);C=Adversitement.base.hbxStrip(C);var E=Adversitement.history.getLastValue("search");if(D.results&&D.results!="0"&&C!=""&&C!=E){Adversitement.history.add("search",C)}}};var A=function(G){var C="";var D=Adversitement.history.read("search");if(D.length>0){D=D[0];if(D!=""){var F=D;var E=Adversitement.history.getLastValue("search");C=F+"|"+E;if(G&&G==true){C=F}Adversitement.history.clear("search")}}return C};return{init:function(C,D){B();if(Adversitement.base.isThisConversionPage()){if(D&&D==true){Adversitement.base.setOrderCustomMetric(C,A(true))}else{Adversitement.base.setCustomMetric(C,A())}}}}}();Adversitement.campaignAttributeHistory=function(){var C=[];var B=function(){var E="";E=Adversitement.base.getParameter("hbx.hra");if(E==""){if(typeof (_hra)!="undefined"&&_hra!=""){E=_hra}}if(E==""){var F=Adversitement.base.getHbxVariable("hqsp");if(F!=null&&F!=""){E=Adversitement.base.getParameter(F)}}if(E==""){var D=Adversitement.base.getHbxVariable("hqsr");if(D!=null&&D!=""){E=Adversitement.base.getReferrerParameter(D)}}if(E==""){for(var G=0;G<C.length;G++){E=Adversitement.base.getParameter(C[G]);if(E!=""){break}}}if(E!=""){Adversitement.history.clear("cmp_attribute");Adversitement.history.add("cmp_attribute",E)}else{var H=Adversitement.base.getCampaign();if(H!=""){Adversitement.history.clear("cmp_attribute")}}};var A=function(){var E="";var D=Adversitement.history.read("cmp_attribute");if(D.length>0){D=D[0];if(D!=""){E=D;Adversitement.history.clear("cmp_attribute")}}return E};return{init:function(D){if(typeof (D)!="undefined"&&D.length>0){C=D}B();if(Adversitement.base.isThisConversionPage()){var E=Adversitement.base.getHbxVariable("hcn");if(E!==null&&E==""){Adversitement.base.setHbxVariable("hcn",A())}}}}}();Adversitement.base.init();
// Everything below this line is optional

//Adversitement.base.campaignParameters = ['cmpid'];
//Adversitement.base.useOrganicCampaigns = ['google.', 'yahoo.', 'live.com', 'ilse.nl'];
//Adversitement.campaignHistory.useDirect = true;

// functions to be executed just before request construction. You can delete these functions if you don't need them.
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.addReferrer);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.fixCommerceVariables);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.firstCampaign);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.lastNoRefresh);
//Adversitement.base.addOnPrePVREvent(Adversitement.custom.getCampaignFromHash);


//Belvilla
//Track google keywords and related landing pages
Adversitement.base.addOnPrePVREvent(function(){
  if(document.referrer.indexOf('google.')!=-1) {
    var q = Adversitement.base.getReferrerParameter('q');
    q = Adversitement.base.hbxStrip(q);
    var url = document.location.href.replace('http://', '').replace('https://', '');
    if(q) {
      Adversitement.base.setCustomMetric(2, q + '|' + url);
    }
  }  
});

// Uncomment lines below to track history.
// Don't forget to set parameter to a Custom Metric that you want to use

//Adversitement.base.addOnPrePVREvent(function() {Adversitement.campaignHistory.init(1, true)}); // uses commerce custom metrics
//Adversitement.base.addOnPrePVREvent(function() {Adversitement.internalSearchHistory.init(2)});
//Adversitement.base.addOnPrePVREvent(function() {Adversitement.campaignAttributeHistory.init(['banner', 'attr'])});

//
// base.js (Fri, 08 Aug 2008 16:42:36 +0200)
//

/**
 * Cookies
 */
 
function getCookie(sName) {
	var aCookie = document.cookie.split('; '), i = aCookie.length, aCrumb;
	while (i--)
	{
 		aCrumb = aCookie[i].split('=');
		if (sName == aCrumb[0])
			return aCrumb[1] != undefined ? unescape(aCrumb[1]) : null;
	}

	return null;
}

function setCookie(sName, sValue) {
	document.cookie = sName + '=' + escape(sValue) + '; path=/; domain=.' + document.domain;
}



/**
 * Tabs
 */
var tabCurrent = null;
var tabCurrentLink = null;

function hideTab(tab) {
	var tabEl = document.getElementById('tab_' + tab);
	if (tabEl == null) return false;

	// Toggle tab
	tabEl.style.display = 'none';
	tabCurrent = null;
}

function showTab(tab) {
	var tabEl = document.getElementById('tab_' + tab);
	if (tabEl == null) return false;

	var tabElLink = document.getElementById('tabLink_' + tab);
	
	// Toggle tab
	tabEl.style.display = '';
	tabCurrent = tabEl;
	
	if(tabElLink != null) {
		addClass(tabElLink, 'active');
		tabCurrentLink = tabElLink;
	}
}

function toggleTab(tab, secondid) {
	var tabEl = document.getElementById('tab_' + tab);
	if (tabEl == null) return false;

	var tabElLink = document.getElementById('tabLink_' + tab);
	if (tabElLink == null) return false;
	
	// Toggle current tab
	if (tabCurrent != null) tabCurrent.style.display = 'none';
	if (tabCurrentLink != null) removeClass(tabCurrentLink, 'active');
	
	// Set current tab
	tabCurrent = tabEl;
	tabCurrentLink = tabElLink;

	// Toggle tab
	tabCurrent.style.display = '';
	addClass(tabCurrentLink, 'active');
	
	// Save to cookie
	if(secondid){
		setCookie('toggleTab[' + secondid + ']', tab);		
	}
	
	// Refresh map due to render bug
	if((tab == 'detailMap' || tab == 'searchMap') && map !== "undefined" && mapRefresh == false) {
		map.checkResize();
		map.setCenter(zoomCenter, zoom);
		mapRefresh = true;
	}
}



/**
 * Vrij/bezet toggle
 */
var popupElInitialClick = false;
var popupEl = null;

function showPeriodPopup(el) {
	popupEl = el;
	popupElInitialClick = true;
	
	var vrijbezetEl = document.getElementById('periodPopup');
	if(vrijbezetEl == null) return;
	
	// Show
	vrijbezetEl.style.top = (Position.positionedOffset(el)[1] + Element.getHeight(el) + 5) + 'px';
	vrijbezetEl.style.display = '';
	
	// Set hide handler;
	document.onclick = function(e) {
		// Ignore initial click
		if(popupElInitialClick) { popupElInitialClick = false; return; }

		if(!e) e = event;
		if(!Event.element(e).descendantOf(vrijbezetEl)) {
			hidePeriodPopup();
		}
	}
}


function hidePeriodPopup() {
	var vrijbezetEl = document.getElementById('periodPopup');
	if(vrijbezetEl == null) return;
	
	// Hide
	vrijbezetEl.style.display = 'none';
	
	// Clear hide handler
	document.onclick = function() {}
}


function togglePeriodPopup(el) {
	var vrijbezetEl = document.getElementById('periodPopup');
	if(vrijbezetEl == null) return;

	if(vrijbezetEl.style.display == 'none') {
		showPeriodPopup(el);
	} else {
		hidePeriodPopup(el);
	}
}

function canSubmitPeriodPopup() {
	var selArrivalPeriodEl = document.getElementById('fh_period');
	if(selArrivalPeriodEl == null) return;

	var selMonthEl = document.getElementById('fh_start_date');
	if(selMonthEl == null) return;

	var selArrivalEl = document.getElementById('choose_arrivaldate');
	if(selArrivalEl == null) return;
	
	// Allow no month selected
	if(selMonthEl.value == "")
		return true;

	// Allow month, arrival period, arrival selected
	if(selMonthEl.value != "" && selArrivalPeriodEl.value != "" && selArrivalEl.value != "")
		return true;
	
	// Deny all others
	return false;
}



/**
 * Opens a popup window
 */
function openWindow(url, width, height, options, winName) {
	var width   = (width)   ? width : 640;
	var height  = (height)  ? height : 480;
	var options = (options) ? options : "scrollbars=yes,menubar=no,toolbar=no,location=no,status=no,resizable=yes";
	var winName = (winName) ? winName : "window";

	var win = window.open(url, name, "width=" + width + ",height=" + height + "," + options);
}


/**
 * Refreshes a page
 */
function refreshPage(){
	var windowLocation = document.compare.sortOption.options[document.compare.sortOption.selectedIndex].value;
	window.location = windowLocation;
}


/**
 * Bookmark
 */
function bookmark(url, title) {
	if (window.sidebar) {
		window.sidebar.addPanel(title, url,"");
	} else if (window.external) {
		window.external.AddFavorite(url, title);
	} else {
		return true;
	}
}


/**
 * Compare
 */
function compare() {
	var inputs = document.getElementsByName('fh_secondid[]'), i = inputs.length, c = 0;
	while(i--) {
		if(inputs[i].checked) c++;
	}
	
	if(c < 1) {
		alert(lCompareCheckMin);
	} else if(c > 3) {
		alert(lCompareCheckMax);
	} else {
		document.compare.app_action.value = 'doCompare';
		document.compare.submit();
	}
}


/**
 * Remove from list
 */
function remove(){
   document.compare.app_action.value = 'removeMyList';
   document.compare.action = "/bekeken.php";
   document.compare.submit();
}


/**
 * Refreshes the book page
 */
function refreshBook() {
	document.book.submit();
}

function refreshBook_cb(el){
  // for now just sumit form, will have some
  // nice code to fresh the values only later

  var cb_ = document.getElementById('insurance_cancel_no');
  if(cb_ == null) return;

  if(el.checked == true){
          cb_.value="yes";
     }else{
          cb_.value="no";
     }

  document.book.submit();
}

//
// ajax.js (Fri, 30 Nov 2007 11:35:19 +0100)
//

/**
 * AJAX functions
 */
if (!window.XMLHttpRequest){
    window.XMLHttpRequest = function(){
        var types = ['Microsoft.XMLHTTP',
                'MSXML2.XMLHTTP.5.0',
                'MSXML2.XMLHTTP.4.0',
                'MSXML2.XMLHTTP.3.0',
                'MSXML2.XMLHTTP' ];
		
        for(var i = 0; i < types.length; i++){ 
            try
			{
                return new ActiveXObject(types[i]);
            }
            catch(e) {}
        }
		
        return undefined;
    }
}

var req = [];


/**
 * Update arrival periods
 */
function ajaxArrivalPeriod(sel, selArrivalPeriod, selMonth, selArrival, isInitial) {
	var selEl = document.getElementById(sel);
	if(selEl == null) return;
	
	var selArrivalPeriodEl = document.getElementById(selArrivalPeriod);
	if(selArrivalPeriodEl == null) return;

	var selMonthEl = document.getElementById(selMonth);
	if(selMonthEl == null) return;

	var selArrivalEl = document.getElementById(selArrival);
	if(selArrivalEl == null) return;
	
	// Store selected period
	var selArrivalPeriodElValue = selArrivalPeriodEl.value;

	// Update arrivals
	if(selMonthEl.value == "") {
		ajaxArrival(sel, selArrivalPeriod, selMonth, selArrival, isInitial);
		return;
	}
	
	// Request
	selArrivalPeriodEl.disabled = true;
	selArrivalPeriodEl.options.length = 0;
	selArrivalPeriodEl.options.add(new Option(lBusy, ''));

	var reqCnt = req.length;
	req[reqCnt] = new XMLHttpRequest();
	
	req[reqCnt].open("GET", "/ajax_vrijbezet.php?" + sel + "=" + selEl.value + "&view=period", true);
	req[reqCnt].onreadystatechange = function(){
		if(req[reqCnt].readyState==4 || req[reqCnt].readyState=="complete"){
			selArrivalPeriodEl.options.length = 0;
			selArrivalPeriodEl.options.add(new Option(lSelectArrivalPeriod, ''));
			
			var e = req[reqCnt].responseXML.documentElement.getElementsByTagName('option'), ec = e.length;
			for(var i = 0; i < ec; i++) {
				var optionValue = e[i].getAttribute('value');
				var option = e[i].firstChild.nodeValue;
				
				selArrivalPeriodEl.options.add(new Option(option, optionValue));
			}
			
			// Restore selected period
			selArrivalPeriodEl.value = ( isInitial ) ? valArrivalPeriod : selArrivalPeriodElValue;
			
			// Update arrivals
			if(isInitial || (selMonthEl.value != "" && selArrivalPeriodEl.value != "") ) {
				ajaxArrival(sel, selArrivalPeriod, selMonth, selArrival, isInitial);
			}
			
			selArrivalPeriodEl.disabled = false;			
		}
	}
	req[reqCnt].send(null);	
}


/**
 * Update arrivals
 */
function ajaxArrival(sel, selArrivalPeriod, selMonth, selArrival, isInitial) {
	var selEl = document.getElementById(sel);
	if(selEl == null) return;
	
	var selArrivalPeriodEl = document.getElementById(selArrivalPeriod);
	if(selArrivalPeriodEl == null) return;
	
	var selMonthEl = document.getElementById(selMonth);
	if(selMonthEl == null) return;
	
	var selArrivalEl = document.getElementById(selArrival);
	if(selArrivalEl == null) return;
	
	// Check required fields
	if(selMonthEl.value == "") {
		selArrivalPeriodEl.disabled = true;
		selArrivalPeriodEl.options.length = 0;
		selArrivalPeriodEl.options.add(new Option(lSelectFirstMonth, ''));
		
		selArrivalEl.disabled = true;
		selArrivalEl.options.length = 0;
		selArrivalEl.options.add(new Option(lSelectFirstMonthPeriod, ''));
		
		return;
	}

	if(selMonthEl.value != "" && selArrivalPeriodEl.value == "") {
		ajaxArrivalPeriod(sel, selArrivalPeriod, selMonth, selArrival, false);
		
		selArrivalEl.disabled = true;
		selArrivalEl.options.length = 0;
		selArrivalEl.options.add(new Option(lSelectFirstPeriod, ''));
		
		return;
	}

	// Store selected arrival
	var selArrivalElText
	if(selArrivalEl.selectedIndex != -1)
		selArrivalElText = selArrivalEl.options[selArrivalEl.selectedIndex].text;
	
	// Request
	selArrivalEl.disabled = true;
	selArrivalEl.options.length = 0;
	selArrivalEl.options.add(new Option(lBusy, ''));

	var reqCnt = req.length;
	req[reqCnt] = new XMLHttpRequest();
	
	req[reqCnt].open("GET", "/ajax_vrijbezet.php?" + sel + "=" + selEl.value + "&" + selArrivalPeriod + "=" + selArrivalPeriodEl.value + "&" + selMonth + "=" + selMonthEl.value, true);
	req[reqCnt].onreadystatechange = function(){
		if(req[reqCnt].readyState==4 || req[reqCnt].readyState=="complete"){
			selArrivalEl.options.length = 0;
			selArrivalEl.options.add(new Option(lSelectArrival, ''));
			
			var e = req[reqCnt].responseXML.documentElement.getElementsByTagName('option'), ec = e.length;
			if(ec == 0) {
				addClass(selArrivalEl, 'inactive');
				
				selArrivalEl.options.length = 0;
				selArrivalEl.options.add(new Option(lArrivalEmpty, ''));					
			} else {
				removeClass(selArrivalEl, 'inactive');
				
				for(var i = 0; i < ec; i++) {
					var optionValue = e[i].getAttribute('value');
					var option = lArrival + " " + e[i].firstChild.nodeValue;
					
					selArrivalEl.options.add(new Option(option, optionValue));
				}
			}
			
			// Restore selected arrival
			selArrivalElText = ( isInitial ) ? valArrival : selArrivalElText;
			
			var i = selArrivalEl.length;
			while(i--) {
				if(selArrivalEl.options[i].text == selArrivalElText) {
					selArrivalEl.selectedIndex = i;
				}
			}

			selArrivalEl.disabled = false;
		}
	}
	req[reqCnt].send(null);	
}


/**
 * Update availability calendar
 */
function ajaxAvailCalendar(secondid, calStartTime, calSize) {
	var calendarContainerEl = document.getElementById('calendarContainer');
	if(calendarContainerEl == null) return;

	var calendarEl = document.getElementById('calendar');
	if(calendarEl == null) return;
	
	// Display busy box
	var calendarBusyEl = displayBusy(calendarContainerEl, lBusy, true);
	
	var reqCnt = req.length;
	req[reqCnt] = new XMLHttpRequest();

	req[reqCnt].open("GET", "/ajax_calendar.php?fh_secondid=" + secondid + "&calStartTime=" + calStartTime + "&calSize=" + calSize + "&lViewPeriods=" + lViewPeriods + "&lCalendarNext=" + lCalendarNext + "&lCalendarPrevious=" + lCalendarPrevious, true);
	req[reqCnt].onreadystatechange = function(){
		if(req[reqCnt].readyState==4 || req[reqCnt].readyState=="complete"){	
			calendarEl.innerHTML = req[reqCnt].responseText;

			// Hide busy box
			hideBusy(calendarBusyEl);
		}
	}
	req[reqCnt].send(null);
}


/**
 * Update availability table
 */
function ajaxAvail(secondid, time, timestamp, isManual) {
	var availContainerEl = document.getElementById('availContainer');
	if(availContainerEl == null) return;

	var availEl = document.getElementById('avail');
	if(availEl == null) return;
	
	var availElBody = firstChild(availEl);
	
	// Display busy box
	var availBusyEl = displayBusy(availContainerEl, lBusy, true);

	//	Clean DOM from empty nodes
	var i = availElBody.childNodes.length;
	while(i--) {
		if(isIgnorable(availElBody.childNodes[i]))
			availElBody.removeChild(availElBody.childNodes[i]);
	}
	
	document.getElementById('availPromoIndication').style.display = 'none';
	
	// Request
	var reqCnt = req.length;
	req[reqCnt] = new XMLHttpRequest();

	req[reqCnt].open("GET", "/ajax_detail.php?fh_secondid=" + secondid + "&timestamp=" + timestamp + "&isManual=" + isManual, true);
	req[reqCnt].onreadystatechange = function(){
		if(req[reqCnt].readyState==4 || req[reqCnt].readyState=="complete"){
			var introEl = document.getElementById('intro');
			if(introEl != null) introEl.innerHTML = lPeriods + ': <strong>' + time + '</strong>';

			// Remove table content
			while(availElBody.childNodes.length > 2) {
				availElBody.removeChild(availElBody.lastChild);
			}

			// Periods
			var periods = req[reqCnt].responseXML.documentElement.getElementsByTagName('period');
			if(periods.length == 0)
				return;
			
			// Periods to table
			var period, periodTitle;
			var avails, avail, availCheckbox, availStart, availEnd, selected;
			var availCount = 0;
			var persons, person, personPrice, personPromo, personPromoPrice;
			var personsRow = false;
			
			for(var i = 0; i < periods.length; i++) {
				period = periods[i];
				periodTitle = period.getElementsByTagName('title')[0].firstChild.nodeValue;
				avails = period.getElementsByTagName('availability');
				
				if(avails.length == 0)
					continue;
				
				for(var j = 0; j < avails.length; j++) {
					availCount++;
					avail = avails[j];
					availCheckbox = avail.getElementsByTagName('checkbox')[0].firstChild.nodeValue;
					availStart = avail.getElementsByTagName('start')[0].firstChild.nodeValue;
					availEnd = avail.getElementsByTagName('end')[0].firstChild.nodeValue;
					selected = avail.getAttribute('selected');
					personPrice = new Array();
					personPromo = new Array();
					personPromoPrice = new Array();
					
					persons = avail.getElementsByTagName('person');
					for(var k = 0; k < persons.length; k++) {
						person = persons[k];
						personPrice.push(person.getElementsByTagName('price')[0].firstChild ? person.getElementsByTagName('price')[0].firstChild.nodeValue : '');
						personPromo.push(person.getElementsByTagName('promo')[0].firstChild ? person.getElementsByTagName('promo')[0].firstChild.nodeValue : '');
						personPromoPrice.push(person.getElementsByTagName('promoprice')[0].firstChild ? person.getElementsByTagName('promoprice')[0].firstChild.nodeValue : '');
					}
					
					if(j > 0) periodTitle = "";

					ajaxAvailRow(availElBody, secondid, periodTitle, availStart, availEnd, personPrice, personPromo, personPromoPrice, availCheckbox, selected);
				}
			}
			
			// Periods not available
			if(availCount == 0) {
				ajaxAvailRowBusy(availElBody, lPeriodsNull);
			}

			// Persons
			ajaxAvailPersons('vbpless', vbpless, timestamp);
			ajaxAvailPersons('vbpmore', vbpmore, timestamp);			

			// Hide busy box
			hideBusy(availBusyEl);
		}
	}
	req[reqCnt].send(null);	
}


/**
 * Adds a row to the availability table
 */
function ajaxAvailRow(availElBody, secondid, periodTitle, start, end, price, promo, promoprice, checkbox, selected) {
	// Create row
	var availElBodyRow = document.createElement('TR');
	availElBodyRow.onmouseover = function() { addClass(this, 'selectedOver'); }
	availElBodyRow.onmouseout = function() { removeClass(this, 'selectedOver'); }
	availElBodyRow.onclick = function() { _hbLink('boeken'); window.location = '/book.php?fh_secondid=' + secondid + '&fh_book_period=' + checkbox; }
	availElBodyRow.title = lBook;
	
	if(periodTitle != "") { addClass(availElBodyRow, 'head'); }
	if(selected != null) { addClass(availElBodyRow, 'selected'); }
	
	availElBody.appendChild(availElBodyRow);

	// Create period column
	var colPeriodEl = document.createElement('TD');
	colPeriodEl.className = 'click period';
	colPeriodEl.innerHTML = periodTitle;
	availElBodyRow.appendChild(colPeriodEl);
	
	// Create period date start column
	var colPeriodDateStartEl = document.createElement('TD');
	colPeriodDateStartEl.className = 'click perioddate';
	colPeriodDateStartEl.innerHTML = start;
	availElBodyRow.appendChild(colPeriodDateStartEl);

	// Create period date spacer column
	var colPeriodDateSpacerEl = document.createElement('TD');
	colPeriodDateSpacerEl.className = 'click perioddatespacer';
	colPeriodDateSpacerEl.innerHTML = "-";
	availElBodyRow.appendChild(colPeriodDateSpacerEl);

	// Create period date end column
	var colPeriodDateEndEl = document.createElement('TD');
	colPeriodDateEndEl.className = 'click perioddate';
	colPeriodDateEndEl.innerHTML = end;
	availElBodyRow.appendChild(colPeriodDateEndEl);

	// Create price columns
	colPriceSpacer = document.createElement('TD');
	colPriceSpacer.className = 'click';
	availElBodyRow.appendChild(colPriceSpacer.cloneNode(true));

	var vbp_end_index = vbp_start_index + 3;
	if(vbp_end_index > price.length)
		vbp_end_index = price.length;	

	for(var i = vbp_start_index; i < vbp_end_index; i++) {
		if(promoprice[i] > 0) {
			priceText = '<span class="strike">' + price[i] + '</span> <span class="special">' + promoprice[i] + "</span>";
		} else {
			priceText = price[i];
		}
		
		if(promo[i] == 1) {
			priceText += ' <img src="/images/exclamation.gif">';
			document.getElementById('availPromoIndication').style.display = '';
		}
	
		var colPrice = document.createElement('td');
		colPrice.className = 'click price';
		colPrice.innerHTML = priceText;
		availElBodyRow.appendChild(colPrice);
	}

	availElBodyRow.appendChild(colPriceSpacer.cloneNode(true));

	var colBook = document.createElement('td');
	colBook.className = 'click book';
	colBook.innerHTML = '<a href="/book.php?fh_secondid=' + secondid + '&fh_book_period=' + checkbox + '">' + lBook + '</a>';
	availElBodyRow.appendChild(colBook);
}

/**
 * Update persons (links)
 */
function ajaxAvailPersons(vbpId, vbp, timestamp) {
	var vbpIdEl = document.getElementById(vbpId);
	if(vbpIdEl == null ) return;
	
	vbpIdEl.setAttribute('href', vbp + "timestamp=" + timestamp);
}


/**
 * Adds a 'busy' row to the availability table
 */
function ajaxAvailRowBusy(availElBody, busy) {
	// Create row
	var availElBodyRow = document.createElement('TR');
	availElBody.appendChild(availElBodyRow);

	// Create column
	var colBusyEl = document.createElement('TD');
	colBusyEl.className = 'busy';
	colBusyEl.colSpan = 4;
	colBusyEl.innerHTML = busy;
	availElBodyRow.appendChild(colBusyEl);
}


/**
 * Display busy box
 */
function displayBusy(el, busy, busyImage) {
	el.style.position = 'relative';

	var content = ""
	if(busyImage) content += '<img src="/styles/images/lightbox/loading.gif" width="16" height="16"> ';
	if(busy) content += busy;

	var elBusyContainer = document.createElement('DIV');
	elBusyContainer.className = 'busyContainer';
	elBusyContainer.style.width = (el.offsetWidth) + 'px';
	elBusyContainer.style.height = (el.offsetHeight) + 'px';
	
	var elBusy = document.createElement('DIV');
	elBusy.className = 'busy';

	elBusy.innerHTML = content;
	el.appendChild(elBusy);
	el.appendChild(elBusyContainer);

	elBusy.style.left = ((elBusyContainer.offsetWidth - elBusy.offsetWidth) / 2) + 'px';
	elBusy.style.top = ((elBusyContainer.offsetHeight - elBusy.offsetHeight) / 2) + 'px';

	new Effect.Appear(elBusyContainer, { duration: 0.2, from: 0.0, to: 0.25 });
	
	return new Array(elBusyContainer, elBusy);
}

/**
 * Hide busy box (takes the returned value from displayBusy as argument)
 */
function hideBusy(els) {
	new Effect.Appear(els[0], { duration: 0.2, from: 0.25, to: 0 });
	
	var i = els.length;
	while(i--) {
		els[i].parentNode.removeChild(els[i]);
	}
}