/** jquery.json-2.3.min.js **/
(function($){var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.toJSON=typeof JSON==='object'&&JSON.stringify?JSON.stringify:function(o){if(o===null){return'null';}
var type=typeof o;if(type==='undefined'){return undefined;}
if(type==='number'||type==='boolean'){return''+o;}
if(type==='string'){return $.quoteString(o);}
if(type==='object'){if(typeof o.toJSON==='function'){return $.toJSON(o.toJSON());}
if(o.constructor===Date){var month=o.getUTCMonth()+1,day=o.getUTCDate(),year=o.getUTCFullYear(),hours=o.getUTCHours(),minutes=o.getUTCMinutes(),seconds=o.getUTCSeconds(),milli=o.getUTCMilliseconds();if(month<10){month='0'+month;}
if(day<10){day='0'+day;}
if(hours<10){hours='0'+hours;}
if(minutes<10){minutes='0'+minutes;}
if(seconds<10){seconds='0'+seconds;}
if(milli<100){milli='0'+milli;}
if(milli<10){milli='0'+milli;}
return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i])||'null');}
return'['+ret.join(',')+']';}
var name,val,pairs=[];for(var k in o){type=typeof k;if(type==='number'){name='"'+k+'"';}else if(type==='string'){name=$.quoteString(k);}else{continue;}
type=typeof o[k];if(type==='function'||type==='undefined'){continue;}
val=$.toJSON(o[k]);pairs.push(name+':'+val);}
return'{'+pairs.join(',')+'}';}};$.evalJSON=typeof JSON==='object'&&JSON.parse?JSON.parse:function(src){return eval('('+src+')');};$.secureEvalJSON=typeof JSON==='object'&&JSON.parse?JSON.parse:function(src){var filtered=src.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered)){return eval('('+src+')');}else{throw new SyntaxError('Error parsing JSON, source is not valid.');}};$.quoteString=function(string){if(string.match(escapeable)){return'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};})(jQuery);
(function(undefined){
function getDate(AS400date){
  var year = AS400date.substring(0,4);
  var month = new String(new Number(AS400date.substring(4,6))-1);
  var day = AS400date.substring(6,8);
  return new Date(year, month, day);
}

function season(startDate, endDate){
  this.startDate;
  if(startDate=="" || startDate=="00000000"){
    this.startDate=new Date();
  }else{
    this.startDate = getDate(startDate);
  };
  this.endDate = getDate(endDate);
}
var seasonList = new Array();

  
      seasonList["280"]=new season("00000000","20130105");
  
      seasonList["208"]=new season("00000000","20130105");
  
      seasonList["578"]=new season("00000000","20130105");
  
      seasonList["752"]=new season("00000000","20130105");
  
      seasonList["528"]=new season("00000000","20130105");
  
      seasonList["056"]=new season("00000000","20130105");
  
      seasonList["250"]=new season("00000000","20130105");
  
      seasonList["724"]=new season("00000000","20130105");
  
      seasonList["040"]=new season("00000000","20130504");
  
      seasonList["756"]=new season("00000000","20130105");
  
      seasonList["203"]=new season("00000000","20130105");
  
      seasonList["348"]=new season("00000000","20130105");
  
      seasonList["616"]=new season("00000000","20130105");
  
      seasonList["246"]=new season("00000000","20130105");
  
      seasonList["380"]=new season("00000000","20130105");
  
      seasonList["300"]=new season("00000000","20130105");
  
      seasonList["442"]=new season("00000000","20130105");
  
      seasonList["703"]=new season("00000000","20130105");
  
      seasonList["191"]=new season("00000000","20130105");
  
      seasonList["352"]=new season("00000000","20130105");
  
      seasonList["100"]=new season("00000000","20130105");
  
      seasonList["792"]=new season("00000000","20120107");
  
      seasonList["705"]=new season("00000000","20130105");
  
      seasonList["008"]=new season("00000000","20120107");
  
      seasonList["499"]=new season("00000000","20130105");
  
      seasonList["807"]=new season("00000000","20110108");
  


// Set country 000 to contain a season which has the combined lowest startdate and the combined highest enddate of all seasons
seasonList["000"] = new season("00000000","20100114");
seasonList["000"].startDate = seasonList["040"].startDate;
seasonList["000"].endDate = seasonList["040"].endDate;
for(s in seasonList){
  if(seasonList[s].startDate.getTime()<seasonList["000"].startDate.getTime()){
    seasonList["000"].startDate = seasonList[s].startDate;
  }
  if(seasonList[s].endDate.getTime()>seasonList["000"].endDate.getTime()){
    seasonList["000"].endDate= seasonList[s].endDate;
  }
} 

Novasol.SeasonList = seasonList;

})();

/** templates.js **/
﻿(function ($, undefined) {
 var templates = {};

 function parse(id, data) {
  if (!templates[id]) {
   var tmp = document.getElementById(id);
   if (tmp) {
    templates[id] = tmp.innerHTML.replace(/^\s*<!--|-->\s*$/g,'');
   }
   else {
    if (window.console) { console.error('[Templates] ' + id + ' Not Found'); }
    return id;
   }
  }
  if (typeof templates[id] != 'function') {
   var fnCode = "try { var p=[], templateId='" + id + "'; p.push('" +
     templates[id]
     .replace(/[\r\t\n]/g, " ")
     .replace(/<\?/g, "\t")
     .replace(/((^|\?>)[^\t]*)'/g, "$1\r")
     .replace(/\t=(.*?)\?>/g, "',$1,'")
     .replace(/\t/g, "');")
     .replace(/\?>/g, "p.push('")
     .replace(/\r/g, "\\'")
     + "');return p.join('');} catch(ex) { if(window.console) { console.error('[Templates] '+templateId+' Exception:', ex); } }";
   templates[id] = new Function("viewData", fnCode);
  }
  return templates[id](data);
 };

 Novasol.Templates = {
  parse: parse
 };

})(jQuery);  
/** jstorage.js **/
(function(e){function k(){if(d.jStorage)try{c=l(String(d.jStorage))}catch(a){d.jStorage="{}"}else d.jStorage="{}";g=d.jStorage?String(d.jStorage).length:0}function h(){try{d.jStorage=m(c),b&&(b.setAttribute("jStorage",d.jStorage),b.save("jStorage")),g=d.jStorage?String(d.jStorage).length:0}catch(a){}}function i(a){if(!a||typeof a!="string"&&typeof a!="number")throw new TypeError("Key name must be string or numeric");return!0}if(!e||!e.toJSON&&!Object.toJSON&&!window.JSON)throw Error("jQuery, MooTools or Prototype needs to be loaded before jStorage!");
var c={},d={jStorage:"{}"},b=null,g=0,m=e.toJSON||Object.toJSON||window.JSON&&(JSON.encode||JSON.stringify),l=e.evalJSON||window.JSON&&(JSON.decode||JSON.parse)||function(a){return String(a).evalJSON()},f=!1,j={isXML:function(a){return(a=(a?a.ownerDocument||a:0).documentElement)?a.nodeName!=="HTML":!1},encode:function(a){if(!this.isXML(a))return!1;try{return(new XMLSerializer).serializeToString(a)}catch(b){try{return a.xml}catch(c){}}return!1},decode:function(a){var b="DOMParser"in window&&(new DOMParser).parseFromString||
window.ActiveXObject&&function(a){var b=new ActiveXObject("Microsoft.XMLDOM");b.async="false";b.loadXML(a);return b};if(!b)return!1;a=b.call("DOMParser"in window&&new DOMParser||window,a,"text/xml");return this.isXML(a)?a:!1}};e.jStorage={version:"0.1.5.3",set:function(a,b){i(a);j.isXML(b)&&(b={_is_xml:!0,xml:j.encode(b)});c[a]=b;h();return b},get:function(a,b){i(a);return a in c?c[a]&&typeof c[a]=="object"&&c[a]._is_xml&&c[a]._is_xml?j.decode(c[a].xml):c[a]:typeof b=="undefined"?null:b},deleteKey:function(a){i(a);
return a in c?(delete c[a],h(),!0):!1},flush:function(){c={};h();return!0},storageObj:function(){function a(){}a.prototype=c;return new a},index:function(){var a=[],b;for(b in c)c.hasOwnProperty(b)&&a.push(b);return a},storageSize:function(){return g},currentBackend:function(){return f},storageAvailable:function(){return!!f},reInit:function(){var a;if(b&&b.addBehavior){a=document.createElement("link");b.parentNode.replaceChild(a,b);b=a;b.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(b);
b.load("jStorage");a="{}";try{a=b.getAttribute("jStorage")}catch(c){}d.jStorage=a;f="userDataBehavior"}k()}};(function(){if("localStorage"in window)try{if(window.localStorage)d=window.localStorage,f="localStorage"}catch(a){}else if("globalStorage"in window)try{window.globalStorage&&(d=window.globalStorage[window.location.hostname],f="globalStorage")}catch(c){}else if(b=document.createElement("link"),b.addBehavior){b.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(b);
b.load("jStorage");var e="{}";try{e=b.getAttribute("jStorage")}catch(g){}d.jStorage=e;f="userDataBehavior"}else{b=null;return}k()})()})(window.jQuery||window.$);  
/** jquery.novasol.js **/
$.fn.extend({
  toggleText: function() {
   var $t = this.eq(0), callbacks={};
   if(typeof $t.data('_tt-state_') === 'undefined') {
    $t.data('_tt-false_', $t.data("toggle-text"));
    $t.data('_tt-true_', $t.text());
    $t.data('_tt-state_', true);
   }
   if(arguments[0] !== true && arguments[0] !== false) {
    $t.data('_tt-state_', !$t.data('_tt-state_'));
    $t.text($t.data('_tt-'+$t.data('_tt-state_')+'_'));
    callbacks[true] = arguments[0];
    callbacks[false] = arguments[1];
   }
   else {
    $t.data('_tt-state_', arguments[0]);
    $t.text($t.data('_tt-'+arguments[0]+'_'));
    callbacks[true] = arguments[1];
    callbacks[false] = arguments[2];
   }
   if(typeof callbacks[$t.data('_tt-state_')] === 'function') {
    callbacks[$t.data('_tt-state_')].apply(this);
   }
   return this;
  }, 
    yellowFade: function() {
        this.stop(true,true).css('background-color','#ffc')
        .animate({
            backgroundColor: '#fff'
        },{
            duration: 750,
            easing: 'easeInQuint'
        });
        return this;
    },
    moveFocusTo: function(selector, completeFn) {
        var o = this.offset(), m = $(selector), mo = m.offset();
   
        if(!m.attr('tabindex')) {
            m.attr('tabindex','0').focus().removeAttr('tabindex');
        }
        else {
            m.focus();
        }
   
   
   
        var n = $('<div></div>');
        n.css({
            position: 'absolute',
            zIndex: '100000',
            border: '2px solid #999',
            top: o.top+'px',
            left: o.left+'px',
            width: this.outerWidth()+'px',
            height: this.outerHeight()+'px'
        }).appendTo(document.body)
        .animate({
            top: (mo.top-4)+'px',
            left: (mo.left-4)+'px',
            width: (m.outerWidth()+4)+'px',
            height: (m.outerHeight()+4)+'px'
        },{
            easing: 'easeOutExpo',
            duration: 1000,
            complete: function() {
                m.yellowFade();
                n.fadeOut({
                    complete: function() {
                        n.remove();
                        typeof completeFn == 'function' && completeFn();
                    }
                });
            }
        });
        return this;
    }
});  
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
 def: 'easeOutQuad',
 swing: function (x, t, b, c, d) {
  //alert(jQuery.easing.default);
  return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
 },
 easeInQuad: function (x, t, b, c, d) {
  return c*(t/=d)*t + b;
 },
 easeOutQuad: function (x, t, b, c, d) {
  return -c *(t/=d)*(t-2) + b;
 },
 easeInOutQuad: function (x, t, b, c, d) {
  if ((t/=d/2) < 1) return c/2*t*t + b;
  return -c/2 * ((--t)*(t-2) - 1) + b;
 },
 easeInCubic: function (x, t, b, c, d) {
  return c*(t/=d)*t*t + b;
 },
 easeOutCubic: function (x, t, b, c, d) {
  return c*((t=t/d-1)*t*t + 1) + b;
 },
 easeInOutCubic: function (x, t, b, c, d) {
  if ((t/=d/2) < 1) return c/2*t*t*t + b;
  return c/2*((t-=2)*t*t + 2) + b;
 },
 easeInQuart: function (x, t, b, c, d) {
  return c*(t/=d)*t*t*t + b;
 },
 easeOutQuart: function (x, t, b, c, d) {
  return -c * ((t=t/d-1)*t*t*t - 1) + b;
 },
 easeInOutQuart: function (x, t, b, c, d) {
  if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
  return -c/2 * ((t-=2)*t*t*t - 2) + b;
 },
 easeInQuint: function (x, t, b, c, d) {
  return c*(t/=d)*t*t*t*t + b;
 },
 easeOutQuint: function (x, t, b, c, d) {
  return c*((t=t/d-1)*t*t*t*t + 1) + b;
 },
 easeInOutQuint: function (x, t, b, c, d) {
  if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
  return c/2*((t-=2)*t*t*t*t + 2) + b;
 },
 easeInSine: function (x, t, b, c, d) {
  return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
 },
 easeOutSine: function (x, t, b, c, d) {
  return c * Math.sin(t/d * (Math.PI/2)) + b;
 },
 easeInOutSine: function (x, t, b, c, d) {
  return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
 },
 easeInExpo: function (x, t, b, c, d) {
  return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
 },
 easeOutExpo: function (x, t, b, c, d) {
  return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
 },
 easeInOutExpo: function (x, t, b, c, d) {
  if (t==0) return b;
  if (t==d) return b+c;
  if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
  return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
 },
 easeInCirc: function (x, t, b, c, d) {
  return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
 },
 easeOutCirc: function (x, t, b, c, d) {
  return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
 },
 easeInOutCirc: function (x, t, b, c, d) {
  if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
  return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
 },
 easeInElastic: function (x, t, b, c, d) {
  var s=1.70158;var p=0;var a=c;
  if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
  if (a < Math.abs(c)) { a=c; var s=p/4; }
  else var s = p/(2*Math.PI) * Math.asin (c/a);
  return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
 },
 easeOutElastic: function (x, t, b, c, d) {
  var s=1.70158;var p=0;var a=c;
  if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
  if (a < Math.abs(c)) { a=c; var s=p/4; }
  else var s = p/(2*Math.PI) * Math.asin (c/a);
  return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
 },
 easeInOutElastic: function (x, t, b, c, d) {
  var s=1.70158;var p=0;var a=c;
  if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
  if (a < Math.abs(c)) { a=c; var s=p/4; }
  else var s = p/(2*Math.PI) * Math.asin (c/a);
  if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
  return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
 },
 easeInBack: function (x, t, b, c, d, s) {
  if (s == undefined) s = 1.70158;
  return c*(t/=d)*t*((s+1)*t - s) + b;
 },
 easeOutBack: function (x, t, b, c, d, s) {
  if (s == undefined) s = 1.70158;
  return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
 },
 easeInOutBack: function (x, t, b, c, d, s) {
  if (s == undefined) s = 1.70158; 
  if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
  return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
 },
 easeInBounce: function (x, t, b, c, d) {
  return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
 },
 easeOutBounce: function (x, t, b, c, d) {
  if ((t/=d) < (1/2.75)) {
   return c*(7.5625*t*t) + b;
  } else if (t < (2/2.75)) {
   return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
  } else if (t < (2.5/2.75)) {
   return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
  } else {
   return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
  }
 },
 easeInOutBounce: function (x, t, b, c, d) {
  if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
  return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
 }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

 // We override the animation for all of these color styles
 jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
  jQuery.fx.step[attr] = function(fx){
   if ( fx.state == 0 ) {
    fx.start = getColor( fx.elem, attr );
    fx.end = getRGB( fx.end );
   }

   fx.elem.style[attr] = "rgb(" + [
    Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
    Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
    Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
   ].join(",") + ")";
  }
 });

 // Color Conversion functions from highlightFade
 // By Blair Mitchelmore
 // http://jquery.offput.ca/highlightFade/

 // Parse strings looking for color tuples [255,255,255]
 function getRGB(color) {
  var result;

  // Check if we're already dealing with an array of colors
  if ( color && color.constructor == Array && color.length == 3 )
   return color;

  // Look for rgb(num,num,num)
  if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
   return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

  // Look for rgb(num%,num%,num%)
  if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
   return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

  // Look for #a0b1c2
  if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
   return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

  // Look for #fff
  if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
   return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

  // Otherwise, we're most likely dealing with a named color
  return colors[jQuery.trim(color).toLowerCase()];
 }
 
 function getColor(elem, attr) {
  var color;

  do {
   color = jQuery.curCSS(elem, attr);

   // Keep going until we find an element that has color, or we hit the body
   if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
    break; 

   attr = "backgroundColor";
  } while ( elem = elem.parentNode );

  return getRGB(color);
 };
 
 // Some named colors to work with
 // From Interface by Stefan Petre
 // http://interface.eyecon.ro/

 var colors = {
  aqua:[0,255,255],
  azure:[240,255,255],
  beige:[245,245,220],
  black:[0,0,0],
  blue:[0,0,255],
  brown:[165,42,42],
  cyan:[0,255,255],
  darkblue:[0,0,139],
  darkcyan:[0,139,139],
  darkgrey:[169,169,169],
  darkgreen:[0,100,0],
  darkkhaki:[189,183,107],
  darkmagenta:[139,0,139],
  darkolivegreen:[85,107,47],
  darkorange:[255,140,0],
  darkorchid:[153,50,204],
  darkred:[139,0,0],
  darksalmon:[233,150,122],
  darkviolet:[148,0,211],
  fuchsia:[255,0,255],
  gold:[255,215,0],
  green:[0,128,0],
  indigo:[75,0,130],
  khaki:[240,230,140],
  lightblue:[173,216,230],
  lightcyan:[224,255,255],
  lightgreen:[144,238,144],
  lightgrey:[211,211,211],
  lightpink:[255,182,193],
  lightyellow:[255,255,224],
  lime:[0,255,0],
  magenta:[255,0,255],
  maroon:[128,0,0],
  navy:[0,0,128],
  olive:[128,128,0],
  orange:[255,165,0],
  pink:[255,192,203],
  purple:[128,0,128],
  violet:[128,0,128],
  red:[255,0,0],
  silver:[192,192,192],
  white:[255,255,255],
  yellow:[255,255,0]
 };
 
})(jQuery);
/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};  
Novasol = window.Novasol || {};

(function($,undefined){

 /* private methods */ 

 function fieldIsValid($field) {
  var isEmail = $field.is('.validate-email'), val = $.trim($field.val());
  if(isEmail) {
   return validateEmail(val, !$field.is('.mandatory'));
  }
  if(!val) {
    return false;
  }
  return true;
 }

 /* event handlers */

 function checkFieldValidity(e) {
  var $field = $(this);
  $field.toggleClass('invalid', !fieldIsValid($field));
 }
 
 function onSubmit(e) {
  e.preventDefault();
  var $t = $(this);
  if(!checkMandatoryFields(this)) {
   $t.trigger('validation-fail');
   return false;
  }
  else {
   $t.trigger('validation-success');
  }
 }
 
 /* public methods */
 
 function validateEmail(email, allowEmpty) { 
  var test = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
  return allowEmpty ? email == '' || test : test;
 }
 
 function checkMandatoryFields(formElm, buttonElm) {
  var success = true, $form = $(formElm), $fields = $form.find('input.mandatory,select.mandatory,textarea.mandatory,input.validate-email');
  for(var i=0,$field,l=$fields.length;i<l;i++) {
   $field = $fields.eq(i);
   if(!fieldIsValid($field)) {
    $field.addClass('invalid');
    success = false;
   }
   else {
    $field.removeClass('invalid');
   }
  }
  if(!success) {
   (buttonElm ? $(buttonElm) : $form.find('button[type=submit]')).moveFocusTo($form.find('.mandatory-notice'));
  }
  return success;
 }

 /* expose public methods */

 Novasol.Forms = {
  validateEmail: validateEmail,
  checkMandatoryFields: checkMandatoryFields
  
 };
 
 /* domReady */
 
 $(function onDomReadyFormsValidation(){
  $(document.body)
   .delegate('form.use-default-validation input.mandatory, form.use-default-validation select.mandatory, form.use-default-validation textarea.mandatory, form.use-default-validation input.validate-email','blur', checkFieldValidity)
   .delegate('form.use-default-validation select.invalid','change', checkFieldValidity)
   .delegate('form.use-default-validation input.invalid, form.use-default-validation select.invalid, form.use-default-validation textarea.invalid','keyup', checkFieldValidity)
   .delegate('form.use-default-validation','submit',onSubmit);
 });
 
})(jQuery);
 
/** utils.js **/
(function($, undefined){
 
 function updateQueryString( url, param, value ) {
  var re = new RegExp( "([?|&])" + param + "=.*?(&|$)","i" );
  if ( url.match( re ) )
   return url.replace( re,'$1' + param + "=" + value + '$2' );
  else
   return url + '&' + param + "=" + value;
 }
 
 function repeatString(stringToRepeat, times, charToJoinOn) {
  var parts = [];

  for (var i = 0; i < times;  i++) {
   parts.push(stringToRepeat);
  }

  return parts.join(charToJoinOn ? charToJoinOn : "");
 }

 Novasol.Utils = {
  repeatString: repeatString,
  updateQueryString: updateQueryString
 };
})(jQuery);
/** newsletter.js **/
(function($,undefined){
 
 function onUnsubscribeClick(e) {
  e.preventDefault(); 
  var email = $('#gb_email').val();
  if(Novasol.Forms.checkMandatoryFields('#newsletter', this)) {
   $('<form action="http://signup.globase.com/" method="post"></form>')
   .append('<input type="hidden" value="351" name="formid">')
   .append('<input type="hidden" value="62" name="licenseid">')
   .append('<input type="hidden" value="55" name="listid">')
   .append('<input type="hidden" value="" name="doubleoptin">')
   .append('<input type="hidden" value="" name="duplicateby">')
   .append('<input type="hidden" value="http://www.novasol.com/home/newsletter/optout-ok.html" name="successurl">')
   .append('<input type="hidden" value="" name="duplicateurl">')
   .append('<input type="hidden" value="http://www.novasol.com/home/newsletter/optout-failed.html" name="failureurl">')
   .append('<input type="hidden" value="" name="doubleoptinsuccessurl">')
   .append('<input type="hidden" value="" name="doubleoptinconfirmedurl">')
   .append('<input type="hidden" value="1" name="unsubscribe">')
   .append('<input type="hidden" name="gb_email" value="'+email+'">')
   .appendTo(document.body).submit();
  }
 }
 
 function onOpenNewsletterSubscribeOverlayClick(e) {
  e.preventDefault();
  Novasol.Overlay.showIframe(455,140,'');
  return false;
 }

 $(function onDomReadyNewsletter(){ //Domready
  $(document.body).delegate('.open-newsletter-subscribe-overlay','click',onOpenNewsletterSubscribeOverlayClick);
  $('#newsletter .unsubscribe').click(onUnsubscribeClick);
  $('#newsletter').bind('validation-success',function(){this.submit();})
 });
 
})(jQuery);
/** toolbox.js **/
(function($, undefined){

 var outsideClickEntity;

 function onCollapsibleToggleClick(e) {
  $(this).closest('.collapsible-container').toggleClass('collapsed');
 }


 function rotateImages(images) {
  var $body = $('#body'), $article = $body.find('div.article'),
   $images = $body.find('img.rotate').add($article.find('div.imgLeft, div.imgRight').not('.no-change, .no-rotate')); 
  for(var i = 0, rnd, neg, l = $images.length; i < l; i++) {
   neg=i%2;
   rnd = Math.floor(Math.random()*7)+1;
   $images.eq(i).css({
    '-moz-transform': 'rotate('+(neg?'-':'')+rnd+'deg)',
    '-webkit-transform': 'rotate('+(neg?'-':'')+rnd+'deg)',
    '-webkit-backface-visibility': 'hidden'
    })[0].style.msTransform = 'rotate('+(neg?'-':'')+rnd+'deg)';
  }  
 }

 function preventDefault(e) {
  e.preventDefault();
  return false;
 }

 function onBodyClick(e) {
  if(outsideClickEntity && !$(e.target).closest(outsideClickEntity.selector).length) {
   outsideClickEntity.callback(e);
   outsideClickEntity = null;
  } 
 }

 function onOpenAsXviewOverlayClick(e) {
  e.preventDefault();
  var url = this.href || $(this).data('href');
  if(url.indexOf('?_xview') != -1) {
   $.get(url,function(data){
    Novasol.Overlay.showHtml(400,300,$(data.replace(/<script/g,'<!--').replace(/<\/script>/g,'-->')).find('div.article').parent().html());
   },'text');   
  }
  else {
   Novasol.Overlay.showIframe(400,300,url);
  }
 }
 
 $(function onDomReadyToolbox() { //dom-ready
  $(document.body).delegate('.block-paste','paste',preventDefault)
  .delegate('.block-copy','copy',preventDefault)
  .delegate('.collapsible-toggle','click',onCollapsibleToggleClick)
  .delegate('.open-as-xview-overlay','click',onOpenAsXviewOverlayClick)
  .mousedown(onBodyClick);

  rotateImages();
 });
 
 $.extend({
  bindOutsideClick: function(selector, callback) {
   outsideClickEntity = {
    selector: selector,
    callback: callback
   };
  }
 });

})(jQuery);
(function($,undefined){
 
 var $header;
 
 function onSalesMarketClick(e) {
  e.preventDefault();
  Novasol.Overlay.showHtml(450, 237, Novasol.Templates.parse('sales-market-overlay-template'));
 }
 
 function hideActive(){ 
  $header.find('.active').removeClass('active'); 
 }
 
 function onActiveMouseleave(e) {
  if(!$(e.relatedTarget).closest('#header .active').length) {
   hideActive();
  }
  
 }
 
 function onLinkClick(selector) {
  return function(e) {
   e.preventDefault();
   var pos = $header.find('a'+selector).position();
   $header.find('.active').removeClass('active');
   $header.find(selector).addClass('active').filter('.dropdown').css('left',(pos.left-10)+'px');
   $.bindOutsideClick('#header .active', hideActive);
  }
 }

 $(function onDomReadyHeader(){
  $header = $('#header').delegate('.active','mouseleave',onActiveMouseleave);
  $header.find('a.sales-market').click(onSalesMarketClick);
  $header.find('a.house-owner').click(onLinkClick('.house-owner')).mouseover(onLinkClick('.house-owner'));
  $header.find('a.partner').click(onLinkClick('.partner')).mouseover(onLinkClick('.partner'));  
  $header.find('a.help').click(onLinkClick('.help')).mouseover(onLinkClick('.help'));  
 });
 
})(jQuery);
/** overlay **/
Novasol = window.Novasol || {};

(function($,undefined){

 var $fullFade, $overlay, $contentWrapper, $transBorder, $content, curHideCallback;

 function onOverlayclick(e) {
  if(e.target == this || e.target == $closeButton[0]) {
   hide();
  }
 }

 function createOverlay() { 
  $fullFade = $('<div id="full-fade"></div>').hide().appendTo(document.body);
  $overlay = $('<div id="overlay"></div>').click(onOverlayclick).hide();
  $transBorder = $('<div class="trans-border"></div>').appendTo($overlay);
  $contentWrapper = $('<div class="content-wrapper"></div>').appendTo($overlay);
  $closeButton = $('<button></button>').appendTo($contentWrapper);
  $content = $('<div class="content"></div>').appendTo($contentWrapper);
  $overlay.appendTo(document.body);
 }
 
 function showIframe(width, height, url, hideCallback) {
  showHtml(width,height,'<iframe src="'+url+'" marginwidth="0" marginheight="0" frameborder="0" framespacing="0" style="width: '+width+'px; height: '+(height-4)+'px;"></iframe>', hideCallback);
 }
 
 function showGrid(columns,height,htmlContent, hideCallback) {
  var width;
  switch(columns) {
   case 1: width=141;break;
   case 2: width=298;break;
   case 3: width=455;break;
   case 4: width=612;break;
   case 5: width=769;break;
   case 6: width=926;break;
   default: width=141;
  }
  
  showHtml(width, height, $('<div class="grid-row"></div>').append($('<div class="grid g'+columns+'"></div>', hideCallback).append(htmlContent)));
 }

 function showHtml(width, height, htmlContent, hideCallback) {
  var contentWrapperHeight = height + 32, // compensate for 16px top/bottom margin
    contentWrapperWidth = width + 54, // compensate for 27px left/right margin
    transBorderHeight = contentWrapperHeight + 16 + 2, //8px larger on top/bottom + compensate for 1px border * 2
    transBorderWidth = contentWrapperWidth + 16 + 2; //8px larger on left/right + compensate for 1px border * 2
  
  if(!$overlay) { 
    createOverlay(); 
  }
  var transBorder = { 
   height: (transBorderHeight)+'px',
   width: (transBorderWidth)+'px',
   marginLeft: (-1 * transBorderWidth / 2) + 'px', //half width
   marginTop: (-1 * transBorderHeight / 2) + 'px'//half height
  },
  contentWrapper = { 
   height: contentWrapperHeight + 'px', 
   width: contentWrapperWidth + 'px', 
   marginLeft: (-1 * contentWrapperWidth / 2 -1) + 'px', 
   marginTop:  (-1 * contentWrapperHeight / 2 -1) + 'px' 
  };

  if($overlay.is(':hidden')) {
   $transBorder.css(transBorder);
   $contentWrapper.css(contentWrapper);
   $content.html(htmlContent);
   $fullFade.show();
   $overlay.show();      
  }
  else {
   $transBorder.animate(transBorder,{ duration: 150});
   $contentWrapper.animate(contentWrapper,{ duration: 150});
   $content.html(htmlContent);
  }
  
  if(typeof hideCallback==='function') {
   curHideCallback = hideCallback;
  }
  else {
   curHideCallback = null;
  }
 }
 
 function hide() {
  if($overlay) {
   $fullFade.hide();
   $overlay.hide();
   $content.html('');
   curHideCallback && curHideCallback();
  }
 }
 
 function OnKeyup(e) {
  if(e.keyCode == 27) {//esc
   hide();
  }
 }

 Novasol.Overlay = {
  showGrid: showGrid,
  showHtml: showHtml,
  showIframe: showIframe,
  hide: hide
 }; 
 
 $(function onDomReadyOverlay(){
  $(document).keyup(OnKeyup).delegate('#overlay div.content .hide-overlay', 'click', hide);
 });
 
})(jQuery);
 
/** Catalogue.js **/

if(Novasol.context === "cataloguelist_301") {

 (function($,undefined){

  var dataFromNotes;

  function onAjaxSuccess(data, textStatus, jqXHR) {
   if(data=='success') {
    Novasol.Overlay.showGrid(2,100,$('#catalogue-order-success-template').html());
   }
   else {
    Novasol.Overlay.showGrid(2,135,$('#catalogue-order-fail-template').html());
   }
  }

  function onAjaxFailure(jqXHR, textStatus, errorThrown) {
   Novasol.Overlay.showGrid(2,135,$('#catalogue-order-fail-template').html());
  }


  function onOrderCatalogueValidationSuccess(e) {

   $.ajax({
    url: dataFromNotes.catalogueOrderPath,
    type: 'POST',
    data: $(this).serialize(),
    cache: false,
    dataType: 'text',
    success: onAjaxSuccess,
    error: onAjaxFailure
   });
  }

  function onCatalogueClick(e) {
   var $form = $(document.getElementById('catalogue-order-template').innerHTML);
   $form
   .bind('validation-success',onOrderCatalogueValidationSuccess)
   .find('input[name=CATID]').val($(this).attr('data-id'));
   Novasol.Overlay.showGrid(3,330,$form);
  }

  function setDataFromNotes(data) {
   dataFromNotes = data;
  }


  $(function onDomReadyCatalogue(){
   $('#the-catalogue-list').delegate('li','click',onCatalogueClick);
  });

  Novasol.Catalogues = {
   setDataFromNotes: setDataFromNotes
  };

 })(jQuery);

}
/** catalogue.init.js **/
if(Novasol.context === "cataloguelist_301") {
 Novasol.Catalogues.setDataFromNotes({
   catalogueOrderPath: '/CatalogueOrder'
 });
}
if(Novasol.context === "destinations_3") {

 (function($, undefined){
 
  var $map;
 
  function onCountryMouseover(e) {
   var m = new Image();
   m.onload = function() {
    $map.find('.overlay').attr('src',m.src).show();
   };
   m.src = '/site/redesign/img/mapHilight_'+$(this).attr('data-id')+'.png';
  
  }
 
  function onCountryMouseout(e) {
   $map.find('.overlay').hide();
  }

  $(function onDomReadyMapOfEurope(){
   var domMap = document.getElementById('map-of-europe');
   if(!domMap) {
    return;
   }
   var $m = $(domMap);
   $map = $m.find('div.map-of-europe');
   $m.find('div.map-of-europe-country-list')
   .delegate('a','mouseover',onCountryMouseover)
   .delegate('a','mouseout',onCountryMouseout);
  });
 })(jQuery);
}
/** owner_contact_form.js **/
(function($, undefined){
 
 
 function onCurrentlyRentingChange(e) {
  $('#owner-contact .currently-renting-conditional').toggle($(this).val() == 'yes');
 }
 
 $(function onDomReadyOwnerContactForm(){
  $('#owner-contact-currently-renting').change(onCurrentlyRentingChange);
  $('#owner-contact').bind('validation-success',function(){this.submit();});
 });
 
 
 
})(jQuery);
/** Calendar.js **/

(function($,undefined){

 var dataFromNotes;

 function createCalendar(newSettings){
  var settings,targetCurrentTime;


  settings = $.extend({},Novasol.calendar.settings,newSettings);


  // Set current date's time part to zero
  targetCurrentTime = Novasol.calendar.functions.parseDateString($(settings.target).val());
  if(targetCurrentTime){
   settings.currentDate = targetCurrentTime;
  }
  settings.currentDate = getCleanTimeFromDate(settings.currentDate || new Date());
  // Ensure startDate
  settings.startDate = getCleanTimeFromDate(settings.startDate || new Date(settings.currentDate));
  if(settings.currentDate<settings.startDate){
   settings.currentDate = new Date(settings.startDate);
  }
  // Ensure lastDate
  settings.lastDate = getCleanTimeFromDate(settings.lastDate || new Date(settings.currentDate.getFullYear()+1,settings.currentDate.getMonth(),settings.currentDate.getDate()));

  settings.name = Novasol.calendar.baseName+Novasol.calendar.counter;

  // The whole calendar is surrounded by a wrapper
  var html = "<div id=\""+settings.name+"\" class=\"nosoCalendar-wrapper\">";
  html += createInnerCalendarHTML(settings);
  html += "</div>";

  if(settings.inline){
   $(settings.target).append(html);
  }else{
   Novasol.Overlay.showHtml(298,230,html);
  }

  // Store calendar specific data for manipulation
  Novasol.calendar.calendars[settings.name] = {
   hoverIn:Novasol.calendar.functions.defaultHoverIn,
   hoverOut:Novasol.calendar.functions.defaultHoverOut,
   select:Novasol.calendar.functions.defaultSelect(settings),
   prevMonth:Novasol.calendar.functions.defaultPrevMonth(settings),
   nextMonth:Novasol.calendar.functions.defaultNextMonth(settings),
   setMonth:Novasol.calendar.functions.defaultSetMonth(settings),
   id: Novasol.calendar.counter,
   close:Novasol.calendar.functions.defaultClose(settings.name),
   settings:settings,
   getMonthDropDownHTML:getMonthDropDownHTML(settings),
   markDatesAsSelected:markDatesAsSelected(settings),
   redraw:redrawCalendar
  };

  // attach events
  $("#"+settings.name)
  .delegate(".nosoCalendar-date.selectable","mouseenter",function(){
   Novasol.calendar.calendars[settings.name].hoverIn($(this))
  })
  .delegate(".nosoCalendar-date.selectable","mouseleave",function(){
   Novasol.calendar.calendars[settings.name].hoverOut($(this))
  })
  .delegate(".nosoCalendar-date.selectable","click",function(){
   Novasol.calendar.calendars[settings.name].select($(this))
  })
  .delegate(".nosoCalendar-month-control-previous","click",function(){
   Novasol.calendar.calendars[settings.name].prevMonth()
  })
  .delegate(".nosoCalendar-month-control-next","click",function(){
   Novasol.calendar.calendars[settings.name].nextMonth()
  });

  Novasol.calendar.counter++;

  return Novasol.calendar.calendars[settings.name];
 }

 function createInnerCalendarHTML(settings){
  var date = new Date(settings.currentDate),
  statusObject = {},
  currentDate = new Date(date),
  weekDay,
  selectable,
  i,
  previousStatus = "",
  newStatus = "",
  html = [],
  tempDate,
  tempDate2,
  weekInMonth = false,
  seasonCode,
  sysTexts = dataFromNotes.text;

  currentDate.setDate(1);

  for (var monthCount = 0, len = settings.months; monthCount < len; monthCount++) {

   tempDate2 = new Date(date);
   tempDate2.setMonth(date.getMonth()+monthCount);


   // Each month then has its own main div
   html[html.length] = "<div class=\"nosoCalendar-month\">";

   // Month is in the future, and user needs a link to go a month back
   if(monthCount==0 && currentDate>settings.startDate){
    html[html.length] = "<div class=\"nosoCalendar-month-control-previous\" title=\"";
    html[html.length] = sysTexts.previousMonth;
    html[html.length] = "\">&nbsp;</div>";
   }
   // Unless month is the last possible and this is the last shown month, the user needs a link to go the next month
   if(monthCount+1==settings.months){
    tempDate = new Date(settings.lastDate);
    tempDate.setMonth(tempDate.getMonth()-(settings.months-1));
    if(currentDate<tempDate) {
     html[html.length] = "<div class=\"nosoCalendar-month-control-next\" title=\"";
     html[html.length] = sysTexts.nextMonth;
     html[html.length] = "\">&nbsp;</div>";
    }
   }

   //Create title
   html[html.length] = "<div class=\"nosoCalendar-month-title\">";
   if(settings.embedMonthSelection && monthCount==0){
    html[html.length] = getMonthDropDownHTML(settings)();
   }else{
    html[html.length] = "<span class=\"m-header\">";
    html[html.length] = sysTexts.month[currentDate.getMonth()];
    html[html.length] = " ";
    html[html.length] = currentDate.getFullYear();
    html[html.length] = "</span>";
   }
   html[html.length] = "</div>";

   html[html.length] = "<div class=\"nosoCalendar-grid\">";

   //Create weekday headers
   html[html.length] = "<div class=\"nosoCalendar-week\">";
   for(weekDay = settings.firstDayOfWeek, i = 0; i<7; i++, weekDay++){
    if(weekDay>6){
     weekDay = 0;
    }
    html[html.length] = "<div class=\"nosoCalendar-weekday nosoCalendar-weekDay"
    html[html.length] = i;
    html[html.length] = " s-header\"><div class=\"nosoCalendar-shortWeekName\">";
    html[html.length] = sysTexts.shortWeekDay[weekDay];
    html[html.length] = "</div></div>";
   }
   html[html.length] = "</div>";

   //Create dates for month
   for(var weekRow = 0; weekRow<6; weekRow++){

    html[html.length] = "<div class=\"nosoCalendar-week\">";

    if(settings.showWeekNumbers && !((monthCount+1)%settings.columns == 0) && currentDate.getMonth()==date.getMonth()+monthCount){
     html[html.length] = "<div class=\"nosoCalendar-weekNo-left\">";
     html[html.length] = calculateWeeknumber(currentDate);
     html[html.length] = "</div>";
    }
    weekInMonth = false;
    for(weekDay = settings.firstDayOfWeek, i = 0; i<7; i++, weekDay++){
     if(weekDay>6){
      weekDay = 0;
     }
     statusObject = settings.statusRange[currentDate.getTime()];
     html[html.length] = "<div class=\"nosoCalendar-weekday nosoCalendar-weekDay";
     html[html.length] = i;
     html[html.length] = "\">";
     if(weekDay!=currentDate.getDay() || currentDate.getMonth()!=tempDate2.getMonth() || currentDate>settings.lastDate){ // before first or after last day of the month
      html[html.length] = "<div class=\"nosoCalendar-status nosoCalendar-status-na\" data-status=\"na\"></div>"; // Insert empty container
     }else{
      weekInMonth = true;
      selectable = " selectable";
      if(settings.restricedSelection && (!statusObject || !statusObject.selectable)){
       selectable = "";
      }
      if(currentDate<settings.startDate){ // before calendar start date
       html[html.length] = "<div class=\"nosoCalendar-status nosoCalendar-status-b\" data-status=\"b\"></div>";
       selectable = "";
      }else{ // Normal day, check with statusRange
       if(statusObject == null || statusObject.status == null){
        statusObject = {
         status:"a"
        };
       }
       newStatus = previousStatus==statusObject.status?statusObject.status:(previousStatus+statusObject.status);
       html[html.length] = "<div class=\"nosoCalendar-status nosoCalendar-status-";
       html[html.length] = newStatus;
       html[html.length] = "\" data-status=\"";
       html[html.length] = newStatus;
       html[html.length] = "\"></div>";
       previousStatus = statusObject.status;
      }

      if(!seasonCode || seasonCode.from>currentDate || seasonCode.to<currentDate){
       seasonCode = getSeasonCode(settings,currentDate);
      }
      if(seasonCode){
       html[html.length] = "<div class=\"nosoCalendar-seasonCode\">";
       html[html.length] = seasonCode.code;
       html[html.length] = "</div>";
      }

      html[html.length] = "<div id=\"";
      html[html.length] = settings.name;
      html[html.length] = "-";
      html[html.length] = currentDate.getTime();
      html[html.length] = "\" class=\"nosoCalendar-date";
      html[html.length] = selectable+"\">";
      html[html.length] = currentDate.getDate()
      html[html.length] = "</div>"; // add date (number)

      currentDate.setDate(currentDate.getDate()+1);
     }
     html[html.length] = "</div>"; // end nosoCalendar-weekday
    }

    tempDate = new Date(currentDate);
    tempDate.setDate(tempDate.getDate()-1);
    if(settings.showWeekNumbers && (monthCount+1)%settings.columns == 0 && weekInMonth){
     html[html.length] = "<div class=\"nosoCalendar-weekNo-right\">";
     html[html.length] = calculateWeeknumber(tempDate);
     html[html.length] = "</div>";
    }

    html[html.length] = "</div>"; //end nosoCalendar-week
   }
   html[html.length] = "</div>"; //end nosoCalendar-grid


   html[html.length] = "</div>"; //end nosoCalendar-month

   if(settings.inline && (monthCount+1)%settings.columns==0){
    html[html.length] = "<div class=\"nosoCalendar-clear\"></div>";
   }
  }

  return html.join('');
 }

 function getSeasonCode(settings,currentDate){
  if(settings.seasonCodes && currentDate){
   for(var x in settings.seasonCodes){
    var startDate = new Date(1*settings.seasonCodes[x].from);
    var endDate = new Date(1*settings.seasonCodes[x].to);
    if(currentDate>=(startDate) && currentDate<=(endDate)){
     return {
      code:settings.seasonCodes[x].code,
      from:startDate,
      to:endDate
     };
    }
   }
  }
  return false;
 }

 function getCleanTimeFromDate(date){
  return new Date(date.getFullYear(),date.getMonth(),date.getDate());
 }

 function getMonthDropDownHTML(settings){
  return function(){
   var tempDate,html,id,sysTexts = dataFromNotes.text;

   id = settings.name+"-monthSelect";
   $("#"+id).remove();
   tempDate = new Date(settings.startDate);
   tempDate.setDate(1);
   html = "<select name=\"monthSelect\" id=\""+id+"\" onchange=\"Novasol.calendar.calendars['"+settings.name+"'].setMonth(new Date(this.value))\">";

   while(tempDate<=settings.lastDate){
    var value = tempDate.getFullYear()+","+(tempDate.getMonth()+1)+",1";
    var selected = tempDate.getMonth()==settings.currentDate.getMonth() && tempDate.getFullYear() == settings.currentDate.getFullYear()?" selected=\"selected\"":"";
    html += "<option value=\""+value+"\""+selected+">"+sysTexts.month[tempDate.getMonth()]+" "+tempDate.getFullYear()+"</option>";
    tempDate.setMonth(tempDate.getMonth()+1);
   }
   html += "</select>"

   return html;
  }
 }

 function calculateWeeknumber(date){
  var daynum, weeknum;
  var year = date.getFullYear();
  var newYear = new Date(year,0,1);
  var modDay = newYear.getDay();
  if (modDay == 0) modDay=6; else modDay--;

  daynum = ((Date.UTC(year, date.getMonth(), date.getDate(), 0, 0, 0, 0) - Date.UTC(year,0,1,0,0,0)) /1000/60/60/24) + 1;
  if (modDay < 4 ) {
   weeknum = Math.floor((daynum+modDay-1)/7)+1;
  } else {
   weeknum = Math.floor((daynum+modDay-1)/7);
   if (weeknum == 0) {
    year--;
    var prevNewYear = new Date(year,0,1);
    var prevmodDay = prevNewYear.getDay();
    if (prevmodDay == 0) prevmodDay = 6; else prevmodDay--;
    if (prevmodDay < 4) weeknum = 53; else weeknum = 52;
   }
  }

  return + weeknum;
 }

 function defaultHoverIn(elmDate,customDuration){
  var data = extractDataFromId(elmDate.prop("id")),
  endDate = new Date(data.date),
  currentDate = new Date(data.date),
  elmCurrentDate,
  status,
  elmCurrentStatus,
  currentStatus,
  calendarFunctions  = Novasol.calendar.functions,
  settings = Novasol.calendar.calendars[data.calendarID].settings,
  duration = customDuration || settings.duration;

  endDate.setDate(endDate.getDate()+duration);

  while(currentDate<=endDate){
   elmCurrentDate = $( "#"+data.calendarID+"-"+currentDate.getTime() );
   if(elmCurrentDate.length>0){
    status = "h";
    elmCurrentStatus = elmCurrentDate.siblings(".nosoCalendar-status").first();
    currentStatus = calendarFunctions.getElmStatus(elmCurrentStatus);
    if(duration>1){
     if(currentDate.getTime()==data.date.getTime()){
      status = currentStatus.substring(0,1)+"h";
     }else if(currentDate.getTime()==endDate.getTime()){
      status = "h"+(currentStatus.length==1?currentStatus:currentStatus.substring(1));
     }
    }
    markElmAsStatus( elmCurrentStatus , status );
   }
   currentDate.setDate(currentDate.getDate()+1);
  }
 }

 function getStatusOfStatusElm(elm){
  return elm.data("status");
 }

 function markElmAsStatus(elm,status){
  elm.attr("class","nosoCalendar-status nosoCalendar-status-"+status);
 }

 function defaultHoverOut(elmDate,customDuration){
  var data,endDate,currentDate,elmCurrentDate, elmCurrentStatus, duration;

  data = extractDataFromId(elmDate.attr("id"));
  endDate = new Date(data.date);
  currentDate = new Date(data.date);
  duration = customDuration || Novasol.calendar.calendars[data.calendarID].settings.duration;

  endDate.setDate(endDate.getDate()+duration);
  while(currentDate<=endDate){
   elmCurrentDate = $( "#"+data.calendarID+"-"+currentDate.getTime() );
   elmCurrentStatus = elmCurrentDate.siblings(".nosoCalendar-status").first();
   markElmAsStatus( elmCurrentStatus , elmCurrentStatus.data("status") );
   currentDate.setDate(currentDate.getDate()+1);
  }
 }

 function defaultClose(calendarID){
  var elmCalendar;

  elmCalendar = $("#"+calendarID);

  if(elmCalendar.length>0){
   return function(){
    elmCalendar.remove();
    Novasol.calendar.calendars[calendarID].settings.onClose();
    Novasol.calendar.calendars[calendarID] = null;
    Novasol.Overlay.hide();
    return true;
   }
  }
  return null;
 }

 function defaultSelect(settings,elmDate){
  var elmTarget;

  elmTarget = $(settings.target);

  if(elmTarget.prop("tagName")=="INPUT"){
   if(elmDate){
    setElmDateForElmTarget(elmDate,elmTarget);
    return true;
   }else{
    return function (elmDate){
     setElmDateForElmTarget(elmDate,elmTarget);
     settings.onSelect(elmDate,extractDataFromId(elmDate.attr("id")).date);
    }
   }
  }else{
   if(elmDate){
    settings.onSelect(elmDate,extractDataFromId(elmDate.attr("id")).date);
    return true;
   }else{
    return function (elmDate){
     settings.onSelect(elmDate,extractDataFromId(elmDate.attr("id")).date);
    }
   }
  }
  return false;
 }

 function setElmDateForElmTarget(elmDate, elmTarget){
  var data;

  data = extractDataFromId(elmDate.attr("id"));

  elmTarget.val(formatDate(data.date));

  Novasol.calendar.calendars[data.calendarID].close();
 }

 function formatDate(date){
  return date.getDate()+"-"+(date.getMonth()+1)+"-"+date.getFullYear();
 }

 function extractDataFromId(id){
  var calendarID,date;

  calendarID = id.match(Novasol.calendar.baseName+"[0-9]+")[0];
  date = new Date(1*id.substring(calendarID.length+1));

  return {
   calendarID:calendarID,
   date:date
  };
 }

 function setMonth(settings,date){
  if(!date){
   return function (date){
    settings.currentDate = date;
    redrawCalendar(settings);
    settings.onMonthChange(date);
   }
  }else{
   settings.currentDate = date;
   redrawCalendar(settings);
   settings.onMonthChange(date);
   return true;
  }
 }

 function nextMonth(settings){
  return function (){
   var newDate = new Date(settings.currentDate);
   var finalDate = new Date(settings.lastDate);
   newDate.setMonth(newDate.getMonth()+1);
   finalDate.setMonth(finalDate.getMonth()-(settings.months-1));
   if(newDate<finalDate){
    if(newDate>settings.startDate){
     newDate.setDate(1);
    }
    setMonth(settings,newDate);
   }
  }
 }

 function prevMonth(settings){
  return function (){
   var newDate = new Date(settings.currentDate);
   var startDate = new Date(settings.startDate);
   newDate.setMonth(newDate.getMonth()-1);
   startDate.setDate(1);
   if(newDate>=startDate){
    if(newDate>settings.startDate){
     newDate.setDate(1);
    }
    setMonth(settings,newDate);
   }
  }
 }

 function redrawCalendar(settings){
  var elmCalendar = $("#"+settings.name);
  elmCalendar.html(createInnerCalendarHTML(settings));
  $("#"+settings.name+"-monthSelect").val(""+settings.currentDate.getFullYear()+","+(settings.currentDate.getMonth()+1)+",1");
 }

 function defaultOnSelect(elmDate){}
 function defaultOnClose(){}
 function defaultOnMonthChange(date){}

 function parseDateString(dateString){
  if(dateString){
   var date = dateString.split("-");
   if(date.length==3){
    return new Date(date[2],1*date[1]-1,date[0]);
   }
  }
  return null;
 }

 function markDatesAsSelected(settings, fromDate, duration){
  return function(fromDate,duration){
   var elmDate, currentStatus, newStatus, temp = new Date(fromDate), i, elmSelected, len;

   // First we remove all previously selected dates
   elmSelected = $("#"+settings.name+" .nosoCalendar-status[oldstatus]");
   for (i = 0, len = elmSelected.length;i<len; i++){
    elmDate = elmSelected.eq(i);
    newStatus = elmDate.data("oldstatus");
    markElmAsStatus(elmDate,newStatus);
    elmDate.data("status", newStatus).removeData("oldstatus").removeAttr("oldstatus");
   }

   // Then we mark the new dates as selected
   for (i = 0; i <= duration; i++) {
    elmDate = $("#"+settings.name+"-"+temp.getTime()).siblings(".nosoCalendar-status");
    if(elmDate && elmDate.data("status")){
     currentStatus = elmDate.data("status");
     if(i==0){
      newStatus = currentStatus.substr(0,1)+"s";
     }else if(i==duration){
      newStatus = "s"+(currentStatus.length==1?currentStatus:currentStatus.substr(1));
     }else{
      newStatus = "s";
     }
     elmDate.data("oldstatus",currentStatus).data("status",newStatus).attr("oldstatus",currentStatus);
     markElmAsStatus(elmDate,newStatus);
     temp.setDate(temp.getDate()+1);
    }
   }
  }
 }

 function nextSaturdayFormatted(){
  var date = new Date();
  date.setDate( date.getDate() + ( 6 - ( date.getDay() ) ) );
  return formatDate(date);
 }

 function setDataFromNotes(data) {
  dataFromNotes = data;
  Novasol.calendar.settings.showWeekNumbers = data.showWeekNumbers;
 }

 Novasol.calendar = {
  setDataFromNotes: setDataFromNotes,
  settings : {
   months:1, // How many months to show at the same time
   startDate:new Date(), // Defines which date to start the calendar
   currentDate:new Date(), // Defines which date we are currently at
   inline:false, // if the calendar should be inline or overlay
   target:"body", // the dom object css identifier defining where the calendar should appear
   showWeekNumbers: true, // show or hide the week numbers
   columns:2, // When more than one months is shown, how many columns should they use
   embedMonthSelection:true, // Should a month selector dropdown be shown after month name?
   firstDayOfWeek:1, // Sets first day of week. 0 = sunday, 1 = monday, 2 = tuesday etc. Default is 1 (monday)
   statusRange:[], // an array of objects [{status,selectable}], use timeInMillis as position in array
   restricedSelection: false, // set to true of disable all days as selectable by default
   duration:0, // Number of days user selects
   lastDate:null, // Defines the last day in the calendar. If null last date will be currentDate plus one year
   seasonCodes: [], // Array of seasoncodes [{"code":"E","from":"1320102000000","to":"1325286000000"}]
   onSelect:defaultOnSelect,
   onClose:defaultOnClose,
   onMonthChange:defaultOnMonthChange
  },
  baseName : "nosoCalendar-",
  counter : 0,
  create : createCalendar,
  calendars : [],
  functions : {
   defaultHoverIn:defaultHoverIn,
   defaultHoverOut:defaultHoverOut,
   defaultSelect:defaultSelect,
   defaultClose:defaultClose,
   defaultPrevMonth:prevMonth,
   defaultNextMonth:nextMonth,
   defaultSetMonth:setMonth,
   getElmStatus:getStatusOfStatusElm,
   formatDate:formatDate,
   parseDateString:parseDateString,
   extractDataFromId:extractDataFromId,
   nextSaturdayFormatted:nextSaturdayFormatted
  }
 };


})(jQuery);
/** Calendar.init.js **/

Novasol.calendar.setDataFromNotes({
 showWeekNumbers: true,
 text : {
  month:["",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  ""],
  shortWeekDay:["Dom",
  "Lun",
  "Mar",
  "Mer",
  "Gio",
  "Ven",
  "Sab"],
  previousMonth:"Clicca per il mese precendente",
  nextMonth:"Clicca per il mese seguente"
 },

});
/** jquery.placeholder.js **/
(function ($) {

 var className = 'has-active-placeholder',
   targetSelector = 'input[placeholder], textarea[placeholder]',
   nativeSupport = 'placeholder' in document.createElement('input');
  
 $.fn.placeholder = function () {
  if (nativeSupport) return this;

  var b = function() {
   if(this.value === '') {
    this.value = this.getAttribute('placeholder');
    $(this).addClass(className);
   }     
  };

  this.blur(b)
  .focus(function() {
   var $this = $(this);
   if(this.value == this.getAttribute('placeholder') && $this.hasClass(className)) {
    this.value = '';
    $this.removeClass(className);
   }
  })
  .change(function() {
   var $this = $(this);
   if($this.hasClass(className) && this.value != this.getAttribute('placeholder')) {
    $this.removeClass(className)
   }
  });

  var i = this.length;
  while(i--) {
   b.apply(this[i]);
  }
  return this;
 };

 if (!nativeSupport) {
  var origValFn = $.fn.val;

  $(function onDomReadyJqueryPlaceholder() {
   $(targetSelector).placeholder();
   $('form').submit(function () {
    var $fields = $(this).find(targetSelector), i = $fields.length;
    while(i--) {
     if($fields[i].value == $fields[i].getAttribute('placeholder') && $fields.eq(i).hasClass(className)) {
      $fields[i].value = '';
      $fields.eq(i).removeClass(className);
     }
    }
   });
  });

  $.fn.val = function () {
   if(!arguments.length) {
    var $elm = this.eq(0), elm = this[0];
    if(elm && $elm.hasClass(className) && elm.value == elm.getAttribute('placeholder')) {
     return '';
    }
   }
   return origValFn.apply(this, arguments);
  };
 }
})(jQuery);
/** frontpage.js **/

if(Novasol.context === "homepage_0") {

 (function($){
 
  var $pictureSetWrappers, 
  timeOfDomReady,
  cycleInterval = 5000,
  fadeOutDuration = 1500,
  $overlay,
  $dots,
  $images,
  $xlHeaders,
  $mHeaders,
  nextPictureSet,
  curWrapper,
  cycleData;
 
  function getNextWrapper() {
   return curWrapper ? 0 : 1;
  }

  function loadNextPictureSet() {
   var nextWrapper = getNextWrapper();
   $images.eq(nextWrapper).prop('src',cycleData[nextPictureSet].img);
   $xlHeaders.eq(nextWrapper).text(cycleData[nextPictureSet].xlHeader);
   $mHeaders.eq(nextWrapper).text(cycleData[nextPictureSet].mHeader);
  }


  function cycleImageAndText() {
   var nextWrapper = getNextWrapper();
   $dots.removeClass('active').eq(nextPictureSet).addClass('active');
   $pictureSetWrappers.eq(curWrapper).fadeOut(fadeOutDuration, function(){
    $pictureSetWrappers.eq(nextWrapper).css('z-index',2);
    $pictureSetWrappers.eq(curWrapper).css('z-index',1).show();
    $overlay.prop('href',cycleData[nextPictureSet].href);
    curWrapper = nextWrapper;
    nextPictureSet = nextPictureSet < cycleData.length - 1 ? nextPictureSet+1 : 0;   
    loadNextPictureSet();
   });   
  } 
 
  function onDomreadyFrontpage() {
   var $tmp = $('#body div.frontpage-big-picture');
   if(!$tmp.length) {
    return;
   }
   $overlay = $tmp.find('a.overlay');
   $pictureSetWrappers = $tmp.find('div.picture-set-wrapper');

   var i = cycleData.length, html='';
   while(i--) {
    html +='<span></span>';
   }
   $dots = $(html).eq(0).addClass('active').end().appendTo($tmp.find('div.dots'));
   $images = $pictureSetWrappers.find('img.fullwidth-image');
   $xlHeaders = $pictureSetWrappers.find('span.xl-header');
   $mHeaders = $pictureSetWrappers.find('span.m-header');
   nextPictureSet = 1;
   curWrapper = 0; 
   timeOfDomReady = new Date().getTime();
  } 
 
  function onWindowLoadFrontpage(){
   if(!$images) {
    return;
   }
   loadNextPictureSet();
   var mSecBetweenDomReadyAndLoad = new Date().getTime() - timeOfDomReady;
   var timeout = cycleInterval - mSecBetweenDomReadyAndLoad;
   timeout = timeout < 1000 ? 1000 : timeout;
   setTimeout(function() {
    cycleImageAndText();
    setInterval(cycleImageAndText,cycleInterval);
   },timeout);
  
  }
 
  $(onDomreadyFrontpage);
  $(window).load(onWindowLoadFrontpage);
 
  Novasol.Frontpage = {
   init: function(data) {
    cycleData = data;
   }
  };
 
 })(jQuery);

}
/** frontpage.init.js **/
if(Novasol.context==="homepage_0"){Novasol.Frontpage.init([{   href: '/destinazioni/croazia.html',   img: '/site/nov/pictures/header-958x270/frontpage/holiday-rental-croatia-cil599.jpg',   xlHeader: 'Croazia: più di 4000 alloggi',   mHeader: '... per un'indimenticabile e rilassante vacanza al mare!'  },{   href: 'LINK=KGIN-76MJPC',   img: '/site/nov/pictures/header-958x270/frontpage/holiday-rental-france-fbc408.jpg',   xlHeader: 'Francia in fiore',   mHeader: 'Prenota la tua vacanza in Francia per il 2012'  },{   href: '/destinazioni/norvegia.html',   img: '/site/nov/pictures/header-958x270/frontpage/holiday-rental-norway-n36005.jpg',   xlHeader: 'Settimana bianca in Austria',   mHeader: 'Scegli il cottage o l'appartamento per le tue vacanze sulla neve'  },{   href: '/destinazioni/danimarca.html',   img: '/site/nov/pictures/header-958x270/frontpage/summer-house-denmark-f09256.jpg',   xlHeader: 'Case e appartamenti in tutta Italia',   mHeader: 'Trascorri il tuo Natale o Capodanno in Italia'  },{   href: '/destinazioni/germania.html',   img: '/site/nov/pictures/header-958x270/frontpage/holiday-rental-germany-dmk500.jpg',   xlHeader: 'Esplora la Spagna ...',   mHeader: '... da Nord a Sud case e appartamenti per le vacanze!'  }])}

Novasol = window.Novasol || {};

(function ($, undefined) {
 var config = {},
 cacheName = "quicksearch-settings",
 calendarMap = {},
 currentCountry,
 $forms = [],
 $quickSearchBox = [],
 $overlays = [],
 previousDurationValue;

 function onTabClick(event) {
  var dataTab = $(this).attr('data-tab');

  // Change the quick search containers
  $(".quicksearch-box .grid-row").removeClass("active").addClass("inactive");
  $([".quicksearch-box .grid-row.", dataTab].join("")).removeClass("inactive").addClass("active");

  // Change the anchors
  $("div.quicksearch-box.tabs div.tab-container a").each((function (dataTab) {
   return function () {
    var that = $(this),
    elementDataTab = that.attr("data-tab"),
    isInactive = elementDataTab === dataTab;

    that.removeClass(isInactive ? "inactive" : "active").removeClass("low-prio-copy").addClass(isInactive ? "active" : "inactive").addClass(isInactive ? "" : "low-prio-copy");
   };
  })(dataTab));
 }

function onSubmit(event) {
  var country = $(this).find('select.C').val();
  var houseNumberSearch = $(this).attr("data-formtype"); // housenumbersearch
  var action = "";

  var target = $(event.target),
   productNumberContainer = target.find("input[name='HN']"),
   productNumbers = [];

  if (productNumberContainer.length) {
   target.find("input.refnr").each(function (index, element) {
    var value = $(this).val();

    if (value !== "") {
     productNumbers.push(value);
    }
   });

   productNumberContainer.val(productNumbers.join(":"));
  }

  if (houseNumberSearch == "housenumbersearch" && !productNumbers.length) {
   $forms.find("input.refnr:first").addClass("invalidSearch");

   return false;
  }

  // Remove the name attribute from input fields that aren't supposed to be submitted but are treated differently
  target.find("input[data-submitvalue='false']").removeAttr("name");

  if (houseNumberSearch == "housenumbersearch" && productNumbers.length == 1) {
   action = ["/p/", productNumbers[0]].join("");
  } else {
   action = ["/r/", country ? country : "000"].join("");
  }

  $(this).prop('action', action);
 }

 function getOptionElement(name, value, selected) {
  return $(document.createElement("option")).attr("value", value).prop("selected", selected ? true : false).html(name).get(0);
 }

 function getCountryOptionList() {
  var areaList = config.areas,
  countryList = [];

  for (var country in areaList) {
   countryList.push([country, areaList[country].name]);
  }

  countryList = countryList.sort(function (a, b) {
   return a[1] == b[1] ? 0 : (a[1] > b[1] ? 1 : -1);
  });

  return $.map(countryList, function (country) {
   return getOptionElement(country[1], country[0]);
  });
 }

 function generateOptionListForArea(optionList, area, level) {
  optionList.push(getOptionElement([Novasol.Utils.repeatString("&nbsp;", level), level > 0 ? "- " : "", area[0]].join(""), area[1]));

  if (area.length === 3) {
   var subareas = area[2] ? area[2].sort(function (a, b) {
    return a[0] == b[0] ? 0 : (a[0] > b[0] ? 1 : -1);
   }) : [];

   for (var i = 0, length = subareas.length; i < length; i++) {
    generateOptionListForArea(optionList, subareas[i], level + 1);
   }
  }
 }

 function showDurationOverlay(previousValue) {
  Novasol.Overlay.showHtml(615, 340, Novasol.Templates.parse("quicksearch-duration-template"), function() {
   var val = parseInt($forms.find("input[name='DUR']").val(), 10);
   
   if (isNaN(val) && previousValue) {
    updateDurationDropDown(previousValue, "select.DUR");
   }
  });

  $("#quicksearch-duration div.col").delegate('a', 'click', function (event) {
   updateDurationDropDown($(event.target).attr("data-value"), "select.DUR");

   Novasol.Overlay.hide();
  });
 }

 function updateDurationDropDown(value, selector) {
  var $optGroup = $(selector).find("optgroup[name='olos']");
  
  $(selector).closest("form").find("input[name='DUR']").each(function() {
   $(this).val(value);
  });

  $optGroup.children("option[name!='altDur']").remove();

  $optGroup.prepend(getOptionElement([value, "nights"].join(" "), value)).children(["option[value='", value, "']"].join(""));

  $(selector).val(value);

  saveState({
   name: "DUR",
   value: value
  })
 }

 function showSwitchDayOverlay(inputConfig) {
  var normalSwitchDay = config.normalSwitchDays[currentCountry];

  if (normalSwitchDay !== undefined && normalSwitchDay != inputConfig.selectedDay) {
   var overlay = $([inputConfig.overlaySelector, inputConfig.switchDayOverlaySelector].join(" "));

   overlay.children("span.message").html(config.switchDayAlertTemplate.replace("[XXX]", config.dateFullTexts[config.normalSwitchDays[currentCountry]]));

   showOverlayRelativeToInputElement({
    inputElement: inputConfig.inputElement,
    overlay: overlay,
    position: "middle-right",
    fadeInMillis: 500
   })

   setTimeout(closeAllOverlays, 3000);
  }
 }

 function getElementOffset($element) {
  var offset = {};

  if ($element.is(":visible")) {
   offset = $element.offset();
  } else {
   offset = $element.show().offset();

   $element.hide();
  }

  return offset;
 }

 function positionAndShowOverlay(inputConfig) { //  inputElement, overlay, position required - fadeInMillis optional
  var leftOverlayOffset, topOverlayOffset, leftInputElementOffset, topInputElementOffset = 0;
  var overlaysOffset = getElementOffset($("div.overlays"));
  var activeGridRowOffset = inputConfig.inputElement.closest("div.grid-row").offset();
  var inputElementOffset = inputConfig.inputElement.offset();

  leftOverlayOffset = overlaysOffset.left - activeGridRowOffset.left;
  topOverlayOffset = overlaysOffset.top - activeGridRowOffset.top;

  leftInputElementOffset = inputElementOffset.left - activeGridRowOffset.left;
  topInputElementOffset = inputElementOffset.top - activeGridRowOffset.top;

  var $overlayElement = inputConfig.overlay.css("cssText", "left: -5000px; top: -5000px");

  switch (inputConfig.position) {
   case "middle-right":
    $overlayElement.css({
     left: ((leftInputElementOffset + inputConfig.inputElement.outerWidth() - 20) - leftOverlayOffset) + "px",
     top: ((topInputElementOffset + (inputConfig.inputElement.outerHeight() / 2) - ($overlayElement.outerHeight() / 2)) - topOverlayOffset) + "px"
    });
    break;
   case "bottom-left":
    $overlayElement.css({
     left: (leftInputElementOffset - leftOverlayOffset - 2) + "px",
     top: (topInputElementOffset + inputConfig.inputElement.outerHeight() - topOverlayOffset + 1) + "px"
    });
    break;
   default:
    throw e(["Position '", position, '" not supported!'].join(""));
    break;
  }

  if (inputConfig.fadeInMillis > 0) {
   $overlayElement.fadeIn(inputConfig.fadeInMillis);
  } else {
   $overlayElement.show();
  }
 }

 function showCalendar(inputConfig) {
  return function (event) {
   event.preventDefault();

   var containerSelector = [inputConfig.overlaySelector, inputConfig.containerSelector].join(" ");
   var calendar = calendarMap[containerSelector];
   var $visibleInputElement = $(inputConfig.inputSelector).filter(":visible");

   if (calendar == null) {
    var currentRawDate = $(inputConfig.hiddenInputSelector).val();
    var options = {
     target: containerSelector,
     inline: true,
     startDate: inputConfig.season.startDate,
     lastDate: inputConfig.season.endDate,
     onSelect: (function (config, $visibleInputElement) {
      return function (element, date) {
       var dateAsLabel = formatDate(date);
       var dateAsValue = [date.getDate(), date.getMonth() + 1, date.getFullYear()].join("-");

       $(config.hiddenInputSelector).val(dateAsValue).attr("data-customvalue", dateAsLabel);
       $(config.inputSelector).val(dateAsLabel);

       saveState({
        name: config.name,
        value: dateAsValue,
        customValue: dateAsLabel
       });
              
       closeCalendar(containerSelector);

       showSwitchDayOverlay({
        overlaySelector: config.overlaySelector,
        switchDayOverlaySelector: config.switchDayOverlaySelector,
        inputElement: $visibleInputElement,
        selectedDay: date.getDay()
       });
      }
     })(inputConfig, $visibleInputElement)
    };

    if (currentRawDate != "") {
     var date = parseDate(currentRawDate);

     if (date != null) {
      options.currentDate = date;
     }
    }

    calendarMap[containerSelector] = Novasol.calendar.create(options);

    $(containerSelector).show().children("button[type='submit']").click(function () {
     closeCalendar(containerSelector);
    });


    //showOverlayContainer(containerSelector);
    showOverlayRelativeToInputElement({
     inputElement: $visibleInputElement,
     overlay: $(containerSelector),
     position: "bottom-left"
    });

    $.bindOutsideClick(containerSelector, function () {
     closeCalendar(containerSelector)
    });
   }
  }
 }

 function closeCalendar(containerSelector) {
  var calendar = calendarMap[containerSelector];

  if (calendar != null) {
   calendar.close();
   delete calendarMap[containerSelector];
  }

  closeAllOverlays();
 }

 function closeAllOverlays() {
  $overlays.hide().children("div").hide();
 }

 function showOverlayRelativeToInputElement(inputConfig) { // inputElement, overlay, position required - fadeInMillis optional
  $overlays.children("div").hide();
  $overlays.show();

  positionAndShowOverlay(inputConfig);
 }

 function showGuestOverlay(event, inputElement) {
  event.preventDefault();

  var numberOfPersonsOverlay = $quickSearchBox.find(".overlays .quicksearch-numberofpersons");

  // Prepopulate dropdowns
  var hiddenElement = $forms.find("input[name='PE']");
  var numberOfPersons = hiddenElement.attr("data-customvalue");

  if (numberOfPersons !== undefined) {
   var splitNumberOfPersons = numberOfPersons.split("-");

   if (splitNumberOfPersons.length == 3) {
    numberOfPersonsOverlay.find("select.adults").children(["option[value='", splitNumberOfPersons[0], "']"].join("")).prop('selected', true);
    numberOfPersonsOverlay.find("select.children").children(["option[value='", splitNumberOfPersons[1], "']"].join("")).prop('selected', true);
    numberOfPersonsOverlay.find("select.infants").children(["option[value='", splitNumberOfPersons[2], "']"].join("")).prop('selected', true);
   }
  }

  showOverlayRelativeToInputElement({
   inputElement: inputElement,
   overlay: numberOfPersonsOverlay,
   position: "bottom-left"
  });

  // Update total when the user changes the dropdowns
  numberOfPersonsOverlay.delegate('select', 'change', function (event) {
   var sum = 0;
   var numberOfPersonsMap = {};

   numberOfPersonsOverlay.find("select").each(function () {
    var that = $(this);
    var persons = parseInt(that.children(":selected").val(), 10);

    numberOfPersonsMap[that.prop("name")] = persons;

    sum += persons;
   });

   inputElement.val([sum, config.guestLabel].join(" "));

   var customValue = [numberOfPersonsMap.adults || 0, numberOfPersonsMap.children || 0, numberOfPersonsMap.infants || 0].join("-");

   hiddenElement.attr("data-customvalue", customValue).val(sum);

   saveState({
    name: "PE",
    customValue: customValue
   })
  });

  $.bindOutsideClick(numberOfPersonsOverlay, closeAllOverlays);

  $(numberOfPersonsOverlay).find("button").click(closeAllOverlays);
 }

 function convertDurationCustomValue(inputValue) {
  return /^\d+w$/.test(inputValue) ? parseInt(inputValue.substring(0, inputValue.length - 1)) * 7 : parseInt(inputValue, 10);
 }

 function formatDate(date) {
  return [config.dateShortTexts[date.getDay()], [date.getDate(), date.getMonth() + 1, date.getFullYear()].join(".")].join(" ");
 }

 function parseDate(date) {
  var parsedDate = null;
  var dateParts = date.split("-");

  if (dateParts.length == 3) {
   parsedDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
  }

  return parsedDate;
 }

 function getCacheSettings() {
  var cachedSettings = $.jStorage.get(cacheName) || {
   settings: []
  };
  var currentTime = (new Date()).getTime();

  if (cachedSettings.timestamp) {
   if ((cachedSettings.timestamp - currentTime) > (172800000 /*2 * 24 * 60 * 60 * 1000*/ )) {
    cachedSettings = {
     settings: []
    };
   }
  }

  if (!cachedSettings.timestamp) {
   cachedSettings.timestamp = currentTime;
  }

  return cachedSettings;
 }

 function initState() {
  var cachedSettings = getCacheSettings();
  var userState = cachedSettings.settings;

  var userStateEntries = $.map(userState, function (userStateEntry) {
   return userStateEntry.name;
  });
  var mergedState = $.merge([], userState);
  var defaults = config.defaults;

  for (var i = 0, length = defaults.length; i < length; i++) {
   var defaultEntry = defaults[i];

   if ($.inArray(defaultEntry.name, userStateEntries) == -1) {
    mergedState.push(defaultEntry);
   }
  }

  var overwrites = config.overwrites || [];

  for (var i = 0, length = overwrites.length; i < length; i++) {
   var overwriteEntry = overwrites[i];

   if ($.inArray(overwriteEntry.name, userStateEntries) == -1) {
    mergedState.push(overwriteEntry);
   } else {
    mergedState[$.inArray(overwriteEntry.name, userStateEntries)] = overwriteEntry;
   }
  }

  var form = $(".quicksearch-box form");

  for (var j = 0, secLength = mergedState.length; j < secLength; j++) {
   var elementState = mergedState[j];
   // var mainElement = $([".quicksearch-box form [name='", elementState.name, "']"].join(""));
   var mainElement = $(form).find([".", elementState.name].join(""));
   var elementType = getElementType(mainElement);
   var dataContainerName = mainElement.attr("data-valuecontainername");

   if (dataContainerName !== undefined) {
    var hiddenInputField = $(form).children(["input[name='", dataContainerName, "']"].join(""));

    var value = elementState.value;
    var customValue = elementState.customValue;

    if (customValue !== undefined) {
     if (elementState.name == "PE") {
      var splitCustomValue = customValue.split("-");

      if (splitCustomValue.length == 3) {
       value = parseInt(splitCustomValue[0], 10) + parseInt(splitCustomValue[1], 10) + parseInt(splitCustomValue[2], 10);
      }
     } else if (elementState.name == "DUR") {
      value = convertDurationCustomValue(customValue);
      previousDurationValue = value;
     }

     hiddenInputField.attr("data-customvalue", customValue);
    } else {
     if (elementState.name == "SD") {
      customValue = formatDate(parseDate(elementState.value));

      elementState.customValue = customValue;

      hiddenInputField.attr("data-customvalue", customValue);
     }
    }

    hiddenInputField.val(elementState.value = value);
   }

   switch (elementType) {
    case "select":
     var hasOptGroups = mainElement.children("optgroup").length > 0;
     var foundElement = false;

     mainElement.find([hasOptGroups ? "optgroup " : "", "option"].join("")).removeAttr('selected');
     foundElement = mainElement.find([hasOptGroups ? "optgroup " : "", elementState.hasOwnProperty("customValue") ? "option[data-label='" : "option[value='", elementState.hasOwnProperty("customValue") ? elementState.customValue : elementState.value, "']"].join("")).prop('selected', true).length > 0;

     if (elementState.name == "C") { // Quick fix to account for lack of update after setting attribute
      var area = findStateObjectByName("R", mergedState);

      var data = {
       value: elementState.value
      }

      if (area) {
       data.preselectedArea = area;
      }

      $(document.body).trigger('countryChanged', data);
     } else if (elementState.name == "DUR") {
      if (!foundElement) {
       updateDurationDropDown(elementState.value, "select.DUR");
       previousDurationValue = elementState.value;
      }
     }

     break;
    case "input[type='text']":
     var inputValue = elementState.value;

     if (elementState.name == "PE") {
      inputValue = [elementState.value, config.guestLabel].join(" ");
     } else if (elementState.name == "SD") {
      inputValue = elementState.customValue;
     }

     mainElement.val(inputValue);

     break;
    case "input[type='hidden']":
     mainElement.val(elementState.value); // Assumption: Hidden fields are stored as direct children of the form element

     break;
    case "input[type='checkbox']":
     if (elementState.value == "checked") {
      mainElement.attr('checked', 'checked');
     } else {
      mainElement.removeAttr('checked');
     }

     break;
   }
  }
 }

function findStateObjectByName(name, mergedState) {
  var stateObject;

  for (var i = 0, length = mergedState.length; i < length; i++) {
   var elementState = mergedState[i];

   if (elementState.name === name) {
    stateObject = elementState;
   }
  }

  return stateObject;
 }

 function saveState(element) {
  var cacheSettings = getCacheSettings();
  var userState = cacheSettings.settings;

  for (var i = 0, length = userState.length; i < length; i++) {
   var userStateEntry = userState[i];

   if (userStateEntry.name == element.name) {
    userState.splice(i, 1);

    break;
   }
  }

  userState.push(element);

  $.jStorage.set(cacheName, cacheSettings);
 }

 function getElementType(element) {
  var tagName = element.prop("tagName");

  if (tagName) {
   tagName = tagName.toLowerCase();
  }

  return tagName == "input" ? ["input[type='", element.get(0).type, "']"].join("") : tagName;
 }

 function getElementValue(element) {
  var type = getElementType(element);
  var returnValue = {
   isCustom: false
  };

  switch (type) {
   case "select":
    var foundElement = element.find([element.children("optgroup").length > 0 ? "optGroup " : "", "option:selected"].join(""));
    var dataLabel = foundElement.attr("data-label");

    returnValue.value = dataLabel !== undefined ? dataLabel : foundElement.val();
    returnValue.isCustom = dataLabel !== undefined;
    break;
   case "input[type='checkbox']":
    returnValue.value = element.is(':checked') ? "checked" : "";
    break;
   default:
    returnValue.value = element.val();
    break;
  }

  return returnValue;
 }

 function onFormElementChange(event) {
  var element = $(event.target);

  if (element) {
   var elementValue = getElementValue(element);
   var containerName = element.attr('data-valuecontainername');
   var parameters = {
    name: containerName !== undefined && containerName != "" ? containerName : element.prop('name')
   };

   if (elementValue.isCustom) {
    parameters.customValue = elementValue.value;
   } else {
    parameters.value = elementValue.value;
   }

   if (true /*elementValue.value != "" && parameters.name !== undefined && parameters.name !== ""*/ ) { //@TODO: Make this a bit more intelligent.........
    saveState(parameters);
   }
  }
 }

 function buildAreaList(isoCode) {
  if (!buildAreaList.cache) {
   buildAreaList.cache = {};
  }

  if (!buildAreaList.cache.hasOwnProperty(isoCode)) {
   var optionList = [getOptionElement(config.areaDefaultText, "")];
   var area = config.areas[isoCode];

   if (area) {
    var areas = area.areas;

    if (areas) {
     var sortedAreas = areas.sort(function (a, b) {
      return a[0] == b[0] ? 0 : (a[0] > b[0] ? 1 : -1);
     });

     if (sortedAreas.length == 1) {
      optionList.pop();
     }

     for (var i = 0, length = sortedAreas.length; i < length; i++) {
      generateOptionListForArea(optionList, sortedAreas[i], 0);
     }
    }
   }

   buildAreaList.cache[isoCode] = optionList;
  }

  return buildAreaList.cache[isoCode];
 }

 function init(inputConfig) {
  $quickSearchBox = $("#body div.quicksearch-box");

  if (!$quickSearchBox.length) {
   return;
  }

  config = inputConfig;

  currentCountry = config.defaultCountry;

  $forms = $quickSearchBox.find("form");
  $overlays = $quickSearchBox.find(" .overlays");

  //add markup/text hidden for SEO purposes
  $quickSearchBox.find(".overlays .quicksearch-numberofpersons").html(Novasol.Templates.parse('quicksearch-numberofpersons-template'));
  $forms.find("select.DUR").append(Novasol.Templates.parse('quicksearch-duration-dropdown-template',{minNights:1}));

  // Handle tab clicks
  $quickSearchBox.find("div.tab-container").delegate('a', 'click', onTabClick);

  // Populate countries list
  $forms.find("select.C").empty().append(getCountryOptionList());

  // Handle country<->area relation
  $forms.find("select.C").change(function () {
   $(document.body).trigger('countryChanged', {value: $(this).children(":selected").val()});
  });

  $forms.find("input.refnr").focus(function(event) {
   $(this).removeClass("invalid");
  })

  // Attach event listeners to "number of guests", "arrival date" and "duration" custom controls
  var inputNumberOfGuests = $forms.find("input.PE"),
  showGuestOverlayFunction = function (event) {
   showGuestOverlay(event, inputNumberOfGuests)
  };

  inputNumberOfGuests.bind('focus', {}, showGuestOverlayFunction);
  $forms.find("img.PE").bind('click', {}, showGuestOverlayFunction);

  var showCalendarFunction = showCalendar({
   hiddenInputSelector: ".quicksearch-box form input[name='SD']",
   inputSelector: ".quicksearch-box form input.SD",
   overlaySelector: ".quicksearch-box .overlays",
   containerSelector: ".quicksearch-arrivaldate",
   switchDayOverlaySelector: ".quicksearch-switchday",
   name: "SD",
   season: config.seasonList
  });

  $forms.find("input.SD").focus(showCalendarFunction);
  $forms.find("img.SD").click(showCalendarFunction);

  $forms.find("select.DUR").change(function (element) {
   var selected = $(this).children("optgroup").children("option:selected");
   var selectedValue = selected.val();
   var name = selected.attr("name");

   $forms.find("input[name='DUR']").val(convertDurationCustomValue(selectedValue));

   if (name != "altDur") {
    $("select.DUR").not($(this)).children("optgroup").children(["option[value='", selectedValue, "']"].join("")).prop("selected", true);
   } else {
    showDurationOverlay(previousDurationValue);

    return false;
   }

   previousDurationValue = selectedValue;
  });

  $(document.body).bind("countryChanged", function (event, data) {
   currentCountry = data.value;

   var optionList = buildAreaList(currentCountry);

   if (optionList.length > 0) {
    var areaSelect = $forms.find("select.R");
    var preselectedArea = data.preselectedArea;

    areaSelect.empty().append(optionList);

    if (preselectedArea) {
     areaSelect.val(preselectedArea.value);
    }
   }
  });

  // Select defaults or stored entry settings
  initState();

  // Handle state changes
  $(document.body).delegate('div.quicksearch-box form', 'change', onFormElementChange);

  // Handle submits
  $(document.body).delegate('div.quicksearch-box form', 'submit', onSubmit);
 }

 Novasol.QuickSearch = {
  init: init,
  saveState: saveState
 };

})(jQuery);
/** quicksearch.init.js **/
$(function () {
var global = {
areas: {

"040": {
     "name": "Austria",
areas: [
["VIENNA", "AWIEN", [["Vienna", "AWI"]]],["AUSTRIA CENTRALE", "CENTR", [["Salisburgo e dintorni", "ASA"]]],["AUSTRIA ORIENTALE", "EASTH", [["Burgenland", "ABU"]]],["AUSTRIA SETTENTRIONALE", "NORTH", [["Bassa Austria", "ANO"],["Alta Austria", "AOE"]]],["AUSTRIA MERIDIONALE", "SOUTH", [["Carinzia", "AKA"],["Stiria", "AST"]]],["AUSTRIA OCCIDENTALE", "WESTH", [["Tirolo", "ATI"],["Vorarlberg", "AVO"]]]
]
    },
"056": {
     "name": "Belgio",
areas: [
["tutto il BELGIO", "BELG", [["Ardenne belghe", "BAR"],["Limburgo", "BLI"],["Fiandre", "BVA"],["Brabante fiammingo", "BVB"]]]
]
    },
"100": {
     "name": "Bulgaria",
areas: [
["BOURGASS", "BBURG", [["Spiaggia del Sole - Costa          Settentrionale", "BGS"],["Costa del Mar Nero - Bourgass      Meridionale", "BGZ"]]],["VARNA", "BVARN", [["Costa del Mar Nero - Varna         Meridionale", "BGM"],["Costa Settentrionale del Mar Nero", "BGN"],["Varna e dintorni", "BGV"]]]
]
    },
"191": {
     "name": "Croazia",
areas: [
["DALMAZIA CENTRALE", "DALMM", [["Isola di Brac", "CDB"],["Isola di Hvar", "CDH"],["Isola di Vis", "CDK"],["Isola Ciovo", "CDM1"],["Isola Drvenik Veli", "CDM2"],["Isola Drvenik Mali", "CDM3"],["Makarska", "CDM4"],["Omis", "CDM5"],["Split", "CDM6"],["Trogir", "CDM7"],["Isola di Solta", "CDO"]]],["DALMAZIA SETTENTRIONALE", "DALMN", [["Biograd", "CDN1"],["Nin", "CDN2"],["Starigrad Paklenica", "CDN3"],["Vir", "CDN4"],["Zara", "CDN5"],["Isola Dugi Otok", "CDU1"],["Isola Rivanj", "CDU10"],["Isola Krknata", "CDU11"],["Isola Ist", "CDU2"],["Isola Iz", "CDU3"],["Isola Molat", "CDU4"],["Isola Pasman", "CDU5"],["Isola Rava", "CDU6"],["Isola Ugljan", "CDU8"],["Isola Zverinac", "CDU9"],["Drnis", "CDV1"],["Prvic", "CDV10"],["Isola di Zirje", "CDV11"],["Isola Kaprije", "CDV2"],["Isola Krapanj", "CDV3"],["Isola Murter", "CDV4"],["Primosten", "CDV5"],["Rogoznica", "CDV6"],["Sibenik", "CDV7"],["Vodice", "CDV8"],["Isola Zlarin", "CDV9"]]],["DALMAZIA MERIDIONALE", "DALMS", [["Riviera di Dubrovnik", "CDD"],["Penisola di Peljesac", "CDP"],["Delta della Neretva", "CDR"],["Isola di Korcula", "CDS"]]],["ISTRIA", "ISTRI", [["Premantura", "CIA"],["Banjole", "CIB"],["Porec", "CIE1"],["Vrsar", "CIE2"],["Fazana", "CIF1"],["Barbariga", "CIF2"],["Costa orientale", "CIK"],["Rabac", "CIK1"],["Labin", "CIK2"],["Krnica", "CIK3"],["Duga Uvala", "CIK4"],["Entroterra dell'Istria", "CIL"],["Barban", "CIL1"],["Ucka", "CIL10"],["Visnjan", "CIL11"],["Vodnjan", "CIL12"],["Zminj", "CIL13"],["Bale", "CIL14"],["Groznjan", "CIL15"],["Buje", "CIL2"],["Buzet", "CIL3"],["Kanfanar", "CIL4"],["Motovun", "CIL5"],["Pazin", "CIL6"],["Sv. Lovrec", "CIL7"],["Svetvincenat", "CIL8"],["Tinjan", "CIL9"],["Medulin", "CIM"],["Pula", "CIP"],["Umag", "CIU1"],["Novigrad", "CIU2"],["Rovinj", "CIV"],["Liznjan", "CIZ"]]],["GOLFO DEL QUARNARO", "KVARN", [["Gorski Kotar", "CKB1"],["Lika", "CKB2"],["Crikvenica", "CKC"],["Krk", "CKK"],["Isole di Cres", "CKL1"],["Isole di Losinj", "CKL2"],["Isola di Ilovik", "CKL3"],["Isola di Susak", "CKL4"],["Novi Vinodolski", "CKN"],["Opatija", "CKO"],["Pag", "CKP"],["Rab", "CKR"],["Karlobag", "CKV1"],["Senj", "CKV2"],["Laghi di Plitvice", "CKV3"]]]
]
    },
"208": {
     "name": "Danimarca",
areas: [
["BORNHOLM", "BORNH", [["Balka, Dueodde, Sømarken", "I50"],["Bornholm sud-occidentale", "I53"],["Bornholm settentrionale/Allinge,   Sandvig", "I55"],["Bornholm orientale/Neksø, Snogebæk", "I57"]]],["FANØ", "FANO", [["Fanø", "M21"]]],["FÜNEN, LANGELAND, TÅSINGE", "FYN", [["Langeland & Tåsinge", "G10"],["Fünen", "G51"]]],["LIMFJORD", "LIMFJ", [["Limfjord", "L50"]]],["LOLLAND, FALSTER, MØN", "LOLL", [["Falster", "K05"],["Lolland", "K10"],["Falster, Marielyst", "K11"],["Møn", "K30"]]],["JUTLAND SETTENTRIONALE", "NORDJ", [["Skagen- Tannis/Ålbæk Bugter", "A01"],["Costa nord-occidentale/Jammerbucht", "A03"],["Costa nord-orientale/Hou, Hals", "A16"]]],["JUTLAND NORD-OCCIDENTALE", "NORVJ", [["Costa nord-occidentale/Vorupør", "B01"],["Jammerbucht/Thorup", "B60"]]],["JUTLAND ORIENTALE", "OSTJ", [["Mols/Ebeltoft", "D01"],["Himmerland orientale", "D60"],["Djursland settentrionale/Fjellerup Strand", "D70"],["Jutland orientale, Juelsminde, Vejle/Fredericia", "D80"]]],["RØMØ", "ROMO", [["Rømø", "R10"],["Wattenmeer sud/Arrild Ferieby", "S10"]]],["SEELAND", "SJELL", [["Seeland settentrionale, Hornbæk,   Gilleleje", "E01"],["Helsingør", "E01X"],["Seeland nord-occidentale, Golfo di Sejerø", "E16"],["Seeland occidentale", "E20"],["Seeland meridionale", "K50"],["Seeland sud-orientale", "K51"]]],["JUTLAND MERIDIONALE", "SONDJ", [["Costa sud-orientale, Hejlsminde", "F02"],["Als", "F09"]]],["COSTA OCCIDENTALE", "VESTK", [["Holmsland Klit Nord/Søndervig", "C01"],["Fjand, Vrist, Vejlby Klit, Thorsminde", "C71"],["Ringkøbing Fjord Nord", "C81"],["Blåvand, Vejers, Ho, Grærup, Mosevrå", "P32"],["Houstrup, Jegum, Henne Strand, Lønne", "P42"],["Ringkøbing Fjord sud, Bork Havn", "P52"],["Holmsland Klit sud, Bjerregård", "P62"],["Kvie Sø", "P85"]]]
]
    },
"246": {
     "name": "Finlandia",
areas: [
["FINLANDIA", "FINLA", [["Zona dei Laghi", "SLA"],["Lapponia", "SNA"],["Finlandia meridionale", "SSA"],["Finlandia occidentale", "SWA"]]]
]
    },
"250": {
     "name": "Francia",
areas: [
["AQUITANIA", "FAQUI", [["Dordogna", "FAD"],["Gironda", "FAG"],["Landes", "FAL"],["Pirenei atlantici", "FAP"],["Lot e Garonna", "FAT"]]],["BRETAGNA", "FBR", [["costa d'Armor", "FBC"],["Finistère", "FBF"],["Ille e Vilaine", "FBI"],["Morbihan", "FBM"]]],["CENTRALE", "FCELO", [["Indre", "FEC"],["Indre-et-Loire", "FEI"]]],["COSTA AZZURRA & CANNES", "FCOTE", [["Alpi marittime", "FCA"],["Cannes", "FCA1"],["Var", "FCV"]]],["ELSASS & LOTHRINGEN", "FELSA", [["Bas-Rhin", "FDB"],["Haut-Rhin", "FDH"],["Meuse", "FTE"],["Vogesen", "FTV"]]],["CORSICA", "FKORS", [["Corsica", "FKO"]]],["LINGUADOCA", "FLANG", [["Aude", "FLA"],["Gard", "FLG"],["Hérault", "FLH"],["Pirenei orientali", "FLP"]]],["NORMANDIA", "FNORM", [["Calvados", "FNC"],["Manica", "FNM"],["Orne", "FNO"],["Senna marittima", "FNS"]]],["PAYS DE LA LOIRE", "FPAYS", [["Loira Atlantica", "FBL"],["Mayenne", "FVA"],["Vandea", "FVE"],["Maine-et-Loire", "FVM"],["Sarthe", "FVS"]]],["POITOU-CHARENTES", "FPOIT", [["Charente Maritime", "FCH"],["Charente", "FJC"],["Deux-Sèvres", "FJD"],["Vienne", "FJV"]]],["PROVENZA-DRÔME-ARDÈCHE", "FPROV", [["Alpi dell'alta Provenza", "FPA"],["Bocche del Rodano", "FPB"],["Drôme", "FPD"],["", "FPS"],["Vaucluse", "FPV"],["Ardèche", "FRA"]]],["MIDI-PIRENEI", "FPYRE", [["Ariège", "FMA"],["Gers", "FMG"],["Lot", "FML"],["Tarn-et-Garonne", "FMN"],["Hautes-Pyrénées", "FMP"],["Tarn", "FMT"]]],["ALPI FRANCESI", "FRHON", [["La Feclaz", "FSB"],["La Tania", "FSL"]]]
]
    },
"280": {
     "name": "Germania",
areas: [
["Germania", "TYSKL", [["Monti dell'Harz e dintorni", "DAN"],["Baviera", "DBA"],["Brandenburg (Tropical Island)", "DBB"],["Berlino", "DBE"],["Lago di Costanza", "DBO"],["Foresta Nera", "DBW"],["Kurhessisches Bergland", "DHE"],["Brughiera di Lüneburg", "DLH"],["Costa del Mecleburgo", "DMK"],["Rügen", "DMR"],["Usedom", "DMU"],["Mecleburgo-Pomerania occidentale", "DMV"],["Bassa Sassonia settentrionale", "DNS"],["Sauerland", "DNW"],["Mosel/Eifel/Hunsrück", "DRP"],["Vogtland/Monti Metalliferi/Sassonia", "DSA"],["Slesia-Holstein", "DSH"],["Turingia", "DTH"],["Unteres Saaletal", "DUS"],["Colline del Weser", "DWE"],["Westerwald", "DWW"]]]
]
    },
"300": {
     "name": "Grecia",
areas: [
["Cipro", "GCY", []],["GREEK ISLANDS", "GISLA", [["Corfù", "GCF"],["Chios", "GCH"],["Kos", "GDK"],["Creta", "GKR"],["Lesbos", "GLE"]]],["GRECIA CONTINENTALE", "GMAIN", [["Atene", "GAT"],["Penisola Calcidica", "GHA"],["Peloponneso", "GPE"],["Pilion", "GPI"]]],["CICLADI", "KYKLA", [["Kea", "GKK"],["Paros", "GKP"],["Syros", "GKS"]]]
]
    },
"352": {
     "name": "Islanda",
areas: [
["ISLANDA", "ISLAN", [["Islanda orientale", "ICE"],["Islanda settentrionale", "ICN"],["Islanda meridonale", "ICS"],["Islanda occidentale", "ICW"]]]
]
    },
"380": {
     "name": "Italia",
areas: [
["VALLE DAOSTA", "IAOST", []],["BASILICATA", "IBASI", [["Costa Ionica", "IBJ"],["Costa Tirrenica", "IBT"]]],["EMILIA ROMAGNA", "IEMIL", [["Entroterra", "IEC"],["Costa Adriatica", "IEK"]]],["FRIULI VENEZIA GIULIA", "IFRIA", [["Entroterra", "IFC"],["Costa Adriatica", "IFK"]]],["CALABRIA", "IKALA", [["Calabria", "IKK"]]],["CAMPANIA", "IKAMP", [["Costiera Amalfitana", "IKA"],["Golfo del Cilento/Salerno", "IKC"],["Golfo di Gaeta e Baia Domizia", "IKG"],["Campania entroterra", "IKL"],["Napoli", "IKN"],["Penisola Sorrentina", "IKS"]]],["LAZIO", "ILATI", [["Costa laziale", "IRK"],["Roma", "IRO"],["Entroterra laziale", "IRU"]]],["LIGURIA", "ILIGU", [["Liguria", "ILL"]]],["MARCHE", "IMARK", [["Marche mare", "IMK"],["Marche campagna", "IMM"]]],["LAGHI DEL NORD", "INORD", [["Lago di Lugano", "ILO"],["Lago di Garda", "IVG"],["Lago di Como", "IVL"],["Lago Maggiore", "IVM"],["Lago d'Orta", "IVO"]]],["PIEMONTE", "IPIEM", [["Piemonte", "IPL"]]],["PUGLIA", "IPUGL", [["Puglia", "ISA"]]],["SARDEGNA", "ISARD", [["Sardegna", "ISD"]]],["SICILIA", "ISIZI", [["Sicilia", "ISS"]]],["TOSCANA", "ITOSC", [["Arezzo/Cortona e dintorni", "ITA"],["Firenze", "ITB"],["Chianti", "ITC"],["Firenze e dintorni", "ITF"],["Grosseto e dintorni", "ITG"],["Lucca e dintorni", "ITL"],["San Gimignano e Volterra", "ITN"],["Pisa e dintorni", "ITP"],["Siena e dintorni", "ITS"],["Montecatini/Pistoia e dintorni", "ITT"]]],["TOSCANA MARE", "ITOSK", [["Isola d'Elba", "ITE"],["Riviera degli Etruschi", "ITK"],["Argentario/Maremma", "ITM"],["Versilia", "ITV"]]],["UMBRIA", "IUMBR", [["Perugia e dintorni", "IUP"],["Spoleto e dintorni", "IUS"],["Lago Trasimeno", "IUT"]]],["VENETO", "IVE", [["Entroterra", "IVC"],["Costa Adriatica", "IVK"],["Venezia", "IVV"]]]
]
    },
"499": {
     "name": "Montenegro",
areas: [
["MONTENEGRO", "MONTE", [["Riviera di Budva", "MNB"]]]
]
    },
"578": {
     "name": "Norvegia",
areas: [
["HORDLAND", "HORDA", [["Hordland meridionale", "N18"],["Hardanger", "N19"],["Hordland settentrionale/Bergen", "N20"]]],["TRØNDELAG", "MIDTN", [["Trøndelag settentrionale", "N38NT"],["Trøndelag meridionale", "N38ST"]]],["MØRE E ROMSDAL", "MORO", [["Sunnmöre", "N27"],["Romsdal", "N28"],["Nordmøre", "N29"]]],["ZONA DI MONTAGNA", "MOUNT", [["Hedmark", "N30"],["Oppland", "N31"],["Buskerud nord", "N33"],["Telemark e Agder interno", "N35"]]],["NORVEGIA SETTENTRIONALE", "NORDN", [["Nordland e Lofoten", "N39NO"],["Troms", "N39TR"]]],["FIORDO DI OSLO E DINTORNI", "OSLOF", [["Akershus", "N37AK"],["Buskerud Sør", "N37BU"],["Østfold", "N37OF"],["Vestfold", "N37VF"]]],["ROGALAND", "ROGA", [["Rogaland meridionale", "N15"],["Ryfylke", "N16"],["Rogaland settentrionale", "N17"]]],["SOGN E FJORDANE", "SOFJ", [["Ytre Sogn", "N21"],["Midt Sogn", "N22"],["Indre Sogn", "N23"],["Sunnfjord", "N24"],["Ydre Nordfjord", "N25"],["Indre Nordfjord", "N26"]]],["NORVEGIA MERIDIONALE", "SOUTN", [["Entroterra", "N34"],["Costa", "N36"]]]
]
    },
"528": {
     "name": "Olanda",
areas: [
["OLANDA", "HOLLA", [["Drenthe", "HDR"],["Frisia", "HFR"],["Gheldria", "HGE"],["Groninga", "HGR"],["Limburgo", "HLI"],["Brabante", "HNB"],["Olanda settentrionale", "HNH"],["Overijssel", "HOV"],["Utrecht", "HUT"],["Zeeland", "HZE"],["Olanda meridionale", "HZH"]]]
]
    },
"616": {
     "name": "Polonia",
areas: [
["POLONIA CENTRALE", "CEPOL", [["Laghi occidentali/Wielkopolska", "PPW"]]],["POLONIA SETTENTRIONALE", "NOPOL", [["Pomerania/Casciubia", "PKA"],["Masuria/distretto dei laghi", "PMA"],["Costa orientale dei Laghi", "PPO"],["Rowy", "PRO"]]],["POLONIA MERIDIONALE", "SOPOL", [["Monti Beskidi/alto Tatra", "PPG"],["Monti Sudeti", "PPZ"]]]
]
    },
"203": {
     "name": "Rep. Ceca",
areas: [
["TUTTA LA REP. CECA", "TJEK", [["Foreste della Boemia", "TBB"],["Montagne della Boemia", "TBG"],["Boemia centrale", "TBM"],["Boemia settentrionale", "TBN"],["Boemia orientale", "TBO"],["Praga", "TBP"],["Boemia meridionale", "TBS"],["Dintorni di Praga", "TBU"],["Boemia occidentale", "TBW"],["Monti Beskidi occidentali", "TMB"],["Le Highlands", "TMH"],["Moravia settentrionale", "TMN"],["Moravia centrale e meridionale", "TMS"]]]
]
    },
"703": {
     "name": "Rep. Slovacca",
areas: [
["Tutta la REP. SLOVACCA", "SLOV", [["Rep. Slovacca centrale", "TSM"],["Rep. Slovacca orientale", "TSO"],["Monti Tatra", "TST"],["Rep. Slovacca occidentale", "TSW"]]]
]
    },
"705": {
     "name": "Slovenia",
areas: [
["Slovenia", "SLOW", [["Regione central", "SCE"],["Costa e Regione del Carso", "SCR"],["Regione della Gorenjska", "SGR"],["Savinjska Regione", "SSR"]]]
]
    },
"724": {
     "name": "Spagna",
areas: [
["ISOLE CANARIE", "CANAR", [["Fuerteventura", "EFU"],["Gran Canaria", "EGR"],["El Hierro", "EHI"],["Lanzarote", "ELA"],["La Palma", "EPA"],["Tenerife", "ETE"]]],["MALLORCA", "EML", []],["SPAGNA CONTINENTALE", "ESPAN", [["Costa del Sol/Andalusia", "EAN"],["Costa Blanca", "EBL"],["Costa Brava", "ECB"],["Costa Calida", "ECC"],["Costa Dorada", "EDO"]]]
]
    },
"752": {
     "name": "Svezia",
areas: [
["SVEZIA CENTRALE", "MELSV", [["Stoccolma/Mälardalen", "S43"],["Värmland/Dalsland", "S45"],["Dalarna", "S46"]]],["SVEZIA SETTENTRIONALE", "NORSV", [["Svezia settentrionale", "S49"]]],["SVEZIA MERIDIONALE", "SYDSV", [["Skåne", "S01"],["Halland", "S02"],["Blekinge", "S03"],["Småland", "S04"],["Västergötland/Göteborg", "S07"],["Bohuslän", "S08"],["Östergötland/Närke", "S09"],["Isola di Öland", "S41"]]],["Isola di Gotland", "S42", []]
]
    },
"756": {
     "name": "Svizzera",
areas: [
["SVIZZERA", "SCHWE", [["SCHWYZ", "ZCE"],["GRAUBUENDEN", "ZGR"]]]
]
    },
"792": {
     "name": "Turchia",
areas: [
["TURCHIA", "TYRKI", [["Costa Egea meridionale e Licia", "TLK"],["Costa Egea settentrionale e        Centrale", "TMA"],["Riviera Turca", "TRV"]]]
]
    },
"348": {
     "name": "Ungheria",
areas: [
["BALATON", "UBALA", [["Balaton sud-occidentale", "UBF"],["Balaton settentrionale", "UBN"],["Balaton meridionale", "UBS"],["Balaton occidentale", "UBW"]]],["tutta l'UNGHERIA", "UNGAR", [["Budapest", "UBP"],["Tata", "UBU"],["Transdanubio settentrionale", "UDI"],["Ansa del Danubio", "UDK"],["Lago di Neusiedl", "UFT"],["Lago di Velence", "UHB"],["Körös-Maros National-Park", "UKM"],["Monti Mátra e Monti Bükk", "UMB"],["Pécs", "UPM"],["Lago di Theis", "UTS"],["Zalakaros", "UWZ"]]]
]
    }
},
areaDefaultText: "Tutte le aree",
guestLabel: "Ospiti",
dateShortTexts: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"],
dateFullTexts: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"],
normalSwitchDays: {
"056": 6,
"100": 6,
"280": 6,
"208": 6,
"246": 6,
"250": 6,
"300": 6,
"528": 6,
"352": 6,
"380": 6,
"191": 6,
"499": 6,
"578": 6,
"616": 6,
"752": 6,
"756": 6,
"703": 6,
"705": 6,
"724": 6,
"203": 6,
"792": 6,
"348": 6,
"040": 6
},
defaults: [
{
name: "C",
value: "208"
},
{
name: "R",
value: ""
},
{
name: "DUR",
customValue: "1w"
},
{
name: "Q25",
value: "checked"
},
{
name: "SD",
value: Novasol.calendar.functions.nextSaturdayFormatted()
}, {
name: "PE",
customValue: "3-0-0"
}
],
overwrites: [],
switchDayAlertTemplate: "Choosing a [XXX] as arrival day increases choice of available holiday homes",
switchDayAlertExceptions: {

"040":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"056":"L'arrivo al venerdì o al sabato aumenterà il numero di proprietà disponibili"
,
"100":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"191":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"208":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"246":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"250":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"280":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"300":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"352":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"380":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"499":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"578":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"528":"L'arrivo al venerdì o al sabato aumenterà il numero di proprietà disponibili"
,
"616":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"203":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"703":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"705":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"724":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"752":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"756":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"792":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"
,
"348":"L'arrivo al sabato aumenterà il numero di proprietà disponibili"

},
defaultCountry: "208",
seasonList: Novasol.SeasonList ? Novasol.SeasonList["208"] : {}
};
if (typeof searchoverwrites === 'undefined') {
Novasol.QuickSearch.init(global);
} else {
Novasol.QuickSearch.init($.extend(true, {}, global, searchoverwrites));
};
});

Novasol = window.Novasol || {};

(function ($, undefined) {
 var favourites = [], recentlyViewedProducts = [], settings = {}, menuBound = false, delegationHandlers = {}, overlayPageCleanupFunctions = [],
 token = null, domain = null, favouritesListID = null, superMenuHasBeenLoaded = false,
 favouritesCacheName = "favourites", recentlyViewedProductsCacheName = "recentlyViewedProducts", settingsCacheName = "favouritesSettings",
 width = 400, height = 400,
 config = {
  loginSuccessCallback: "Novasol.Favourites.loginCompleted",
  loginFailureCallback: "Novasol.Favourites.loginFailed",
  saveSuccessCallback: "Novasol.Favourites.saveCompleted",
  saveFailureCallback: "Novasol.Favourites.saveFailed"
 },
 $container = null, $counter = null, $overlay = null;

 // Service functions
 function doPostSubmit(url, inputParameters) {
  var iframe = $("<iframe />").hide(),
  form = $("<form />").attr({
   method: "post",
   action: url
  }),
  parameters = $.extend(inputParameters, {
   type: "HTML"
  });

  if (parameters) {
   for (var parameter in parameters) {
    var value = parameters[parameter];

    if (value) {
     form.append($("<input />").attr({
      type: "hidden",
      "name": parameter,
      "value": value
     }));
    }
   }
  }

  $(document.body).append(iframe);

  form.appendTo($(iframe).load(function() {
   $(this).remove();
  }).contents().find("body")).submit();
 }

 function formatPresentationURL(inputConfig) {
  var product = inputConfig.product;

  return inputConfig.urlTemplate.replace("%ID%", product.id).replace("%SD%", product.start ? product.start : "").replace("%ED%", product.end ? product.end : "");
 }

 function validateObject(inputConfig, requiredParams) {
  for (var i = 0, length = requiredParams.length; i < length; i++) {
   if (!inputConfig[requiredParams[i]]) {
    throw Error();
   }
  }
 }

 function mapFavourites(inputFavourites) {
  var favourites = [];
  var partMap = {
   n: "id",
   ad: "start",
   dd: "end",
   i: "src"
  };

  for (var i = 0, length = inputFavourites.length; i < length; i++) {
   var inputFavourite = inputFavourites[i];

   favourites[favourites.length] = mapObjectParts(inputFavourite, partMap);
  }

  return favourites;
 }

 // Callbacks
 function loginCompleted(data) {
  if (data.s == 200) {
   token = data.t;
   favouritesListID = data.fl;

   $.cookie("token", token);
   $.cookie("favouritesListID", favouritesListID);

   updateFavourites(mapFavourites(data.f));

   updateSetting("hasUserLoggedInPreviously", true);

   stateChanged();

   Novasol.Overlay.hide();

   $(document.body).trigger("favouritesUpdated", favourites);
  } else {
   handleLoginFailure(data);
  }
 }

 function loginFailed(data) {
  handleLoginFailure(data);
 }

 function handleLoginFailure(data) {
  showLoginPopup({
   showError: true,
   showHint: false,
   email: data.e,
   password: data.p
  });
 }

 function saveCompleted(data) {
  if (data.s == 200) {
   token = data.t;
   favouritesListID = data.fl;

   $.cookie("token", token);
   $.cookie("favouritesListID", favouritesListID);

   updateFavourites(mapFavourites(data.f));

   stateChanged();
   
   showSaveConfirmationPopup({listCreated: true});
   
   $(document.body).trigger("favouritesUpdated", favourites);
  } else {
   handleSaveFailure(data);
  }
 }

 function saveFailed(data) {
  handleSaveFailure(data);
 }

 function handleSaveFailure(data) {
  showSavePopup({
   showError: true,
   showHint: false, 
   email: data.e,
   password: data.p
  });
 }

 function superMenuLoaded() {
  superMenuHasBeenLoaded = true;
  
  updateMenu();
 }

 // Private methods
 function login(inputConfig) {
  var parameters = {
   successCallback: config.loginSuccessCallback,
   failureCallback: config.loginFailureCallback,
   favourites: inputConfig.favourites,
   password: inputConfig.password,
   email: inputConfig.email,
   brand: config.brand
  };

  doPostSubmit([config.safeBaseURL, "/favourites/access"].join(""), parameters);
 }

 function logout() {
  $.cookie("token", null);
  $.cookie("favouritesListID", null);

  $.jStorage.set(favouritesCacheName, []);
  $.jStorage.set(recentlyViewedProductsCacheName, []);

  token = null;
  favouritesListID = null;
  favourites = [];

  stateChanged();
 }

 function save(inputConfig) {
  var parameters = {
   successCallback: config.saveSuccessCallback,
   failureCallback: config.saveFailureCallback,
   password: inputConfig.password,
   email: inputConfig.email,
   favourites: serializeProducts(favourites),
   brand: config.brand
  };

  doPostSubmit([config.safeBaseURL, "/favourites"].join(""), parameters);
 }

 function serializeProducts(products, fieldsToInclude) {
  var serializedProducts = [];

  for (var i = 0, length = products.length; i < length; i++) {
   var product = products[i];

   serializedProducts[serializedProducts.length] = serializeProduct(product, fieldsToInclude);
  }

  return serializedProducts.join(";");
 }

 function serializeProduct(product, fieldsToInclude) {
  return getObjectParts(product, fieldsToInclude || ["id", "start", "end", "src"]).join(":");
 }

 function getObjectParts(object, parts) {
  var objectParts = [];

  for (var i = 0, length = parts.length; i < length; i++) {
   var part = parts[i];
   var value = object[part];

   if (value) {
    objectParts[objectParts.length] = value;
   }
  }

  return objectParts;
 }

 function mapObjectParts(object, partMap) {
  var mappedObject = {};

  for (var part in partMap) {
   if (object[part]) {
    mappedObject[partMap[part]] = object[part];
   }
  }

  return mappedObject;
 }

 function invokeDelegationHandler(delegationHandlers, action, context) {
  if (!delegationHandlers) {
   return;
  }
  var delegationHandler = delegationHandlers[action];

  if (delegationHandler) {
   try {
    delegationHandler(context);
   } catch (e) {
    if (window.console) {
     console.log(e);
    }
   }
  }
 }

 function handleOverlayDelegation(delegationHandlers, overlay) {
  return function() {
   var action = $(this).attr("data-action");

   invokeDelegationHandler(delegationHandlers, action, {
    overlay: overlay || $("#overlay")
   });
  };
 }

 var showLoginPopup = getDefaultOverlayEventHandler({
  templateName: "login",
  delegateSelector: "a, button",
  delegateEvent: "click",
  delegationHandler: "delegationHandlers.overlays.login",
  successFunction: "submit",
  height: 300
 });

 var showSavePopup = getDefaultOverlayEventHandler({
  templateName: "save",
  delegateSelector: "button",
  delegateEvent: "click",
  delegationHandler: "delegationHandlers.overlays.save",
  successFunction: "create",
  height: 300
 });

var showSaveConfirmationPopup = getDefaultOverlayEventHandler({
  templateName: "saveConfirmation",
  delegateSelector: "button",
  delegateEvent: "click",
  height: 150
 });

 var showSendListPopup = getDefaultOverlayEventHandler({
  templateName: "sendList",
  delegateSelector: "button",
  delegateEvent: "click",
  delegationHandler: "delegationHandlers.overlays.sendList",
  successFunction: "send",
  height: 250
 });

 var showClearListPopup = getDefaultOverlayEventHandler({
  templateName: "clearList",
  delegateSelector: "button",
  delegateEvent: "click",
  delegationHandler: "delegationHandlers.overlays.clearList",
  successFunction: "yes",
  height: 150
 });

 var showOpenMyBookingPopup = getDefaultOverlayEventHandler({
  templateName: "openMyBooking",
  delegateSelector: "button",
  delegateEvent: "click",
  delegationHandler: "delegationHandlers.overlays.openMyBooking",
  successFunction: "submit",
  height: 300
 });

 function cleanupAfterOverlayPage() {
  for (var i = 0, length = overlayPageCleanupFunctions.length; i < length; i++) {
   var overlayPageCleanupFunction = overlayPageCleanupFunctions[i];

   if (overlayPageCleanupFunction) {
    try {
     overlayPageCleanupFunction();
    } catch (e) {
     if (window.console) {
      console.log(e);
     }
    }
   }
  }

  overlayPageCleanupFunctions = [];
 }

 function addOverlayPageCleanupFunction(cleanupFunction) {
  overlayPageCleanupFunctions[overlayPageCleanupFunctions.length] = cleanupFunction;
 }

 function showOverlay(inputConfig) {
  Novasol.Overlay.showGrid(2, inputConfig.height || height, inputConfig.content, cleanupAfterOverlayPage);

  return $("#overlay"); // Make Novasol.Overlay return the overlay instead!
 }

 function setPresentationalURLs(entities) {
  for (var i = 0, length = entities.length; i < length; i++) {
   var entity = entities[i];

   entity.imageURL = [config.imageDomain, entity.src].join("");
   entity.housePresentationURL = formatPresentationURL({
    urlTemplate: config.presentationBaseURLTemplate,
    product: entity
   });
  }

  return entities;
 }

 function updateMenu() {
  var presentationalFavourites = setPresentationalURLs($.extend([], favourites));
  var presentationalRecentlyViewedProducts = setPresentationalURLs($.extend([], recentlyViewedProducts));

  $counter.html(["(", favourites.length, ")"].join(""));

  var container = $("#myFavourites").closest("div.content");

  if (menuBound) {
   $("#myFavourites").undelegate("a.functionality", "click");

   menuBound = false;
  }

  container.empty().html(Novasol.Templates.parse(config.templates.menu, {
   counter: favourites.length,
   favourites: presentationalFavourites,
   recentlyViewedProducts: presentationalRecentlyViewedProducts,
   presentationBaseURLTemplate: config.presentationBaseURLTemplate,
   isLoggedIn: token !== null
  }));

  if (!menuBound) {
   menuBound = $("#myFavourites").delegate("a.functionality", "click", function() {
    var handler = delegationHandlers.menu[$(this).attr("data-action")];

    if (handler) {
     handler();
    }
   }).length > 0;
  }
 }

 function updateFavourites(inputFavourites) {
  var newState = inputFavourites || $.jStorage.get(favouritesCacheName);

  $.jStorage.set(favouritesCacheName, newState);
  favourites = newState;
 }

 function getDefaultOverlayEventHandler(inputConfig) {
  return function(contextData) {
   var $newOverlay = showOverlay({
    content: Novasol.Templates.parse(config.templates[inputConfig.templateName], $.extend({isLoggedIn: token !== null}, contextData || {})),
    height: inputConfig.height
   });
   var $form = $newOverlay.find("form");

   cleanupAfterOverlayPage();

   $newOverlay.delegate(inputConfig.delegateSelector, inputConfig.delegateEvent, handleOverlayDelegation(eval(inputConfig.delegationHandler)));

   $form.bind("validation-success", function() {
    var handler = eval([inputConfig.delegationHandler, ".", inputConfig.successFunction].join(""));

    if (handler) {
     handler({
      overlay: $newOverlay
     });
    }
   });

   addOverlayPageCleanupFunction(function() {
    $newOverlay.undelegate(inputConfig.delegateSelector, inputConfig.delegateEvent);

    $form.unbind("validation-success");
   });
  };
 }

 function handleAjaxMailResponse(inputConfig, email, mailSent) {
  var defaultEventHandler = getDefaultOverlayEventHandler(inputConfig);

  defaultEventHandler({
   email: email,
   mailSent: mailSent
  });
 }

 function viewMyFavourites(viewType) {
  return function(data) {
   document.location = [config.viewProductListBaseURL, (serializeProducts(favourites, ["id", "start", "end"]) || "").replace(/:/g,"|").replace(/;/g,":"), "&layout=", viewType].join("");
  };
 }

function openDefaultSearchResultPage() {
  document.location = config.defaultSearchBaseURL.replace("%COUNTRY%", config.defaultSearchCountry);
 }

 function setupDelegationHandlers() {
  delegationHandlers = {
   menu: {
    list: viewMyFavourites("list"),
    gallery: viewMyFavourites("gallery"),
    map: viewMyFavourites("map"),
    open: showLoginPopup,
    save: showSavePopup,
    clear: showClearListPopup,
    send: showSendListPopup,
    openDefaultSearchResultPage: openDefaultSearchResultPage,
    logout: logout,
    openMyBooking: showOpenMyBookingPopup
   },
   overlays: {
    login: {
     submit: function(data) {
      var $overlay = data.overlay;
      var addExistingFavourites = $overlay.find("input[name='ADD']").is(":checked") && favourites.length > 0;
      var loginData = {
       password: $overlay.find("#password").val(),
       email: $overlay.find("#email").val()
      };
      
      if (addExistingFavourites) {
       loginData.favourites = serializeProducts(favourites);
      }

      login(loginData);

     //Novasol.Overlay.hide();
     },
     forgot: getDefaultOverlayEventHandler({
      templateName: "forgot",
      delegateSelector: "button",
      delegateEvent: "click",
      delegationHandler: "delegationHandlers.overlays.forgot",
      successFunction: "submit",
      height: 200
     }),
     cancel: Novasol.Overlay.hide
    },
    save: {
     create: function(data) {
      var $overlay = data.overlay;

      save({
       password: $overlay.find("#password").val(),
       email: $overlay.find("#email").val()
      });

      Novasol.Overlay.hide();
     },
     cancel: Novasol.Overlay.hide
    },
    clearList: {
     yes: function(data) {
      clear();

      Novasol.Overlay.hide();
     },
     no: Novasol.Overlay.hide
    },
    openMyBooking: {
     submit: function(data) {
      var $overlay = data.overlay;
      var bookingNumber = $overlay.find("#bookingNumber").val();
      var productNumber = $overlay.find("#productNumber").val();
      var email = $overlay.find("#email").val();

      cleanupAfterOverlayPage();

      document.location = ["https://secure.novasol.com/booking.nsf/0/", config.salesmarket, config.brand, "_bookshow?opendocument=&H=", productNumber, "&B=", bookingNumber, "&E=", email].join("");
     },
     cancel: Novasol.Overlay.hide
    },
    sendList: {
     send: function(data) {
      var $overlay = data.overlay;
      var sendListReference = $overlay.find("input[type='radio']:checked").val() === "asRef";
      var email = $overlay.find("#email").val();
      var postData = {
       email: email,
       brand: config.brand,
       salesmarket: config.salesmarket
      };
      
      if (sendListReference) {
       postData.favlistid = favouritesListID;
      } else {
       postData.favourites = serializeProducts(favourites, ["id", "start", "end"]);
      }

      if (token) {
       postData.token = token;
      }

      var responseHandlerConfig = {
       templateName: "sendListConfirmation",
       delegateSelector: "button",
       delegateEvent: "click",
       delegationHandler: "delegationHandlers.overlays.sendList.confirmation",
       height: 150
      };

      $.ajax({
       cache: false,
       success: function(data) {
        handleAjaxMailResponse(responseHandlerConfig, email, data.s === 200);
       },
       error: function(jqXHR) {
        handleAjaxMailResponse(responseHandlerConfig, email, false);
       },
       type: "POST",
       data: postData,
       url: [config.baseURL, "/favourites/mails"].join("")
      });
     },
     cancel: Novasol.Overlay.hide,
     confirmation: {
      ok: Novasol.Overlay.hide
     }
    },
    forgot: {
     submit: function(data) {
      var $overlay = data.overlay;
      var email = $overlay.find("#email").val();

      var responseHandlerConfig = {
       templateName: "forgotConfirmation",
       delegateSelector: "button",
       delegateEvent: "click",
       delegationHandler: "delegationHandlers.overlays.forgot.confirmation",
       height: 150
      };

      $.ajax({
       cache: false,
       success: function(data) {
        handleAjaxMailResponse(responseHandlerConfig, email, data.s === 200);
       },
       error: function() {
        handleAjaxMailResponse(responseHandlerConfig, email, false);
       },
       type: "GET",
       data: {
        email: email,
        brand: config.brand,
        salesmarket: config.salesmarket
       },
       url: [config.baseURL, "/favourites/passwords"].join("")
      });
     },
     cancel: Novasol.Overlay.hide,
     confirmation: {
      ok: Novasol.Overlay.hide
     }
    }
   }
  };
 }

 function stateChanged() {
  updateMenu();
 }

 // Public methods

 function add(inputFavourite) {
  validateObject(inputFavourite, ["id","src"]);

  for (var i = 0, length = favourites.length; i < length; i++) {
   var favourite = favourites[i];

   if (favourite && inputFavourite.id == favourite.id) {
    favourites.splice(i, 1);

    break;
   }
  }

  favourites.unshift(inputFavourite);

  updateFavourites(favourites);

  var postSuccessHandler = function() {
   stateChanged();

   $(document.body).trigger("favouriteAdded", inputFavourite);
  };

  if (token) {
   // make request and update favourites based on response
   $.ajax({
    cache: false,
    success: function(data) {
     updateFavourites(mapFavourites(data.f));

     postSuccessHandler();
    },
    error: function() {
     
    },
    type: "PUT",
    data: {
     token: token,
     favourite: serializeProduct(inputFavourite)
    },
    url: [config.baseURL, "/favourites/", favouritesListID].join("")
   });
  } else {
   if (!settings.hasUserLoggedInPreviously) {
    var addCount = settings.addCount || 0;

    if (addCount === 0) {
     showSavePopup({showHint: true});
    }

    updateSetting("addCount", addCount + 1);
   }

   postSuccessHandler();
  }  
 }

 function updateSetting(setting, value) {
  settings[setting] = value;

  $.jStorage.set(settingsCacheName, settings);
 }

 function remove(inputFavourite) {
  validateObject(inputFavourite, ["id"]);

  for (var i = 0, length = favourites.length; i < length; i++) {
   var favourite = favourites[i];

   if (favourite && inputFavourite.id == favourite.id) {
    favourites.splice(i, 1);

    break;
   }
  }

  updateFavourites(favourites);

  var postSuccessHandler = function() {
   stateChanged();

   $(document.body).trigger("favouriteRemoved", inputFavourite);
  };

  if (token) {
   // make request and update favourites based on response
   $.ajax({
    cache: false,
    success: function(data, textStatus, jqXHR) {
     updateFavourites(mapFavourites(data.f));

     postSuccessHandler();
    },
    error: function(jqXHR, textStatus, errorThrown) {

    },
    type: "GET",
    data: {
     token: token,
     favourite: serializeProduct(inputFavourite)
    },
    url: [config.baseURL, "/favourites/", favouritesListID, "/clear"].join("")
   });
  } else {
   postSuccessHandler();
  }
 }

 function clear() {
  favourites = [];

  updateFavourites(favourites);

  var postSuccessHandler = function() {
   stateChanged();

   $('var.is-fav').removeClass('is-fav');
  };

  if (token) {
   $.ajax({
    cache: false,
    success: function(data, textStatus, jqXHR) {
     updateFavourites(mapFavourites(data.f));

     stateChanged();

     postSuccessHandler();
    },
    error: function(jqXHR, textStatus, errorThrown) {

    },
    type: "GET",
    data: {
     token: token,
     favlistid: favouritesListID
    },
    url: [config.baseURL, "/favourites/clear"].join("")
   });
  } else {
   postSuccessHandler();
  }
 }

function isFavourite(id) {
  var returnValue = false;

  for (var i=0, length = favourites.length, favourite; i < length; i++) {
   favourite = favourites[i];

   if (favourite && favourite.id === id) {
    returnValue = true;
    break;
   }
  }

  return returnValue;
 }

 function getProducts() {
  return favourites.slice(0);
 }

 function getContainerElement() {
  return $container;
 }

 function addProductView(product) {
  validateObject(product, ["id", "src"]);

  for (var i = 0, length = recentlyViewedProducts.length; i < length; i++) {
   var recentlyViewedProduct = recentlyViewedProducts[i];

   if (recentlyViewedProduct && product.id == recentlyViewedProduct.id) {
    recentlyViewedProducts.splice(i, 1);

    break;
   }
  }

  recentlyViewedProducts.unshift(mapObjectParts(product, {
   id: "id",
   src: "src"
  }));

  recentlyViewedProducts = recentlyViewedProducts.slice(0, Math.min(recentlyViewedProducts.length, 6));

  $.jStorage.set(recentlyViewedProductsCacheName, recentlyViewedProducts);

  stateChanged();
 }

 function getRecentlyViewedProducts() {
  return recentlyViewedProducts;
 }

function onFavIconClick(e) {
  e.preventDefault();
  e.stopImmediatePropagation();
  e.stopPropagation();
  var $this = $(this);
  if($this.toggleClass('is-fav').hasClass('is-fav')) {
   add($this.data());   
  }
  else {
   $this.removeClass('is-fav')
   remove($this.data());
  }
 }

 function init(inputConfig) {
  var validated = false;

  try {
   validateObject(inputConfig, ["templates", "imageDomain", "presentationBaseURLTemplate", "safeBaseURL", "baseURL", "brand", "salesmarket", "counter", "viewProductListBaseURL", "defaultSearchCountry", "defaultSearchBaseURL"]);
   validateObject(inputConfig.templates, ["login"]);

   validated = true;
  } catch (e) {
   if (window.console) {
    console.log(e);
   }
  }

  if (validated) {
   recentlyViewedProducts = $.jStorage.get(recentlyViewedProductsCacheName) || [];
   favourites = $.jStorage.get(favouritesCacheName) || [];
   settings = $.jStorage.get(settingsCacheName) || {};
   token = $.cookie("token");
   favouritesListID = $.cookie("favouritesListID");

   $(document.body).bind("superMenuLoaded", function() {
    superMenuLoaded();
   });

   //@TODO: Add context to Novasol.Overlay so this doesn't respond gloablly
   $(document.body).bind("overlayHidden", function() {
    cleanupAfterOverlayPage();
   });

   $container = inputConfig.container;
   $counter = inputConfig.counter;
   
   config = $.extend(inputConfig, config);

   // document.domain = document.domain;

   setupDelegationHandlers();

   $(document.body).trigger("favouritesUpdated", favourites);

   var $favIcons = $('var.fav-icon');
   for(var i=0,l=$favIcons.length,$favIcon;i<l;i++) {
    $favIcon = $favIcons.eq(i);
    if(isFavourite($favIcon.attr('data-id'))) {
     $favIcon.addClass('is-fav');
    }    
   }

   $('var.fav-icon').click(onFavIconClick);
  }
 }

 Novasol.Favourites = {
  showLoginPopup: showLoginPopup,
  showSavePopup: showSavePopup,
  showSendListPopup: showSendListPopup,
  showClearListPopup: showClearListPopup,
  showOpenMyBookingPopup: showOpenMyBookingPopup,
  add: add,
  remove: remove,
  clear: clear,
  init: init,
  isFavourite: isFavourite,
  getProducts: getProducts,
  getContainerElement: getContainerElement,
  updateMenu: updateMenu,
  login: login,
  logout: logout,
  loginCompleted: loginCompleted,
  loginFailed: loginFailed,
  saveCompleted: saveCompleted,
  saveFailed: saveFailed,
  addProductView: addProductView
 };

 Novasol.ready(function onDomReadyMyFavorites(){
  Novasol.Favourites.init({
   templates: {
    menu: "myFavouritesSuperMenuTemplate",
    login: "openPreviouslySavedMyFavouritesList",
    save: "createNewMyFavouritesList",
    saveConfirmation: "createNewMyFavouritesListConfirmation",
    sendList: "sendMyFavourites",
    sendListConfirmation: "sendMyFavouritesConfirmation",
    clearList: "clearMyFavourites",
    openMyBooking: "openMyBooking",
    forgot: "forgotMyPassword",
    forgotConfirmation: "forgotMyPasswordConfirmation"
   },
   containers: {
    menu: $("#favorites_supermenu")
   },
   counter: $("span.favoritesCounter"),
   imageDomain: "http://sdc.novasol.com",
   presentationBaseURLTemplate: "/p/%ID%?SD=%SD%&amp;ED=%ED%",
   safeBaseURL: "/MyFavourites",
   baseURL: "/MyFavourites",
   viewProductListBaseURL: "/r/000?RTYPE=wishlist&HN=",
   brand: "NOV",
   salesmarket: "380",
   defaultSearchCountry: 208,
   defaultSearchBaseURL: "/r/%COUNTRY%?PE=3&Q25=Y"
  });
 });
})(jQuery);

(function($,undefined){
 
 var hideTimeout, elmMenus;
 
 function onWindowResize(e) {
  if(elmMenus) {
   
   elmMenus.each(function(){
    var elm = $(this), pos = elm.offset();
    elm.data('superMenuTop').css({
     top: (pos.top-11) +'px',
     left: (pos.left-15) +'px'
    });
    elm.data('superMenuBottom').css({
     top: (pos.top+29-11) +'px',
     left: (pos.left-44-19) +'px'
    });
   });
  }
 }
 
 function onSuperMenuAnchorOver() {
  var elm = $(this).focus();
  $(document.body).children('.superMenuTop,.superMenuBottom').hide();
  clearTimeout(hideTimeout);
  elm.data('superMenuTopContent').html(elm.html());
  elm.data('superMenuTop').show();
  elm.data('superMenuBottom').show();
  onSuperMenuOut();
 }
 
 
 function onSuperMenuOver(){
  clearTimeout(hideTimeout);
 }
 
 function onSuperMenuOut() {
  hideTimeout = setTimeout(function(){
   $(document.body).children('.superMenuTop,.superMenuBottom').hide();
  },100);    
 }
 
 
 
 $.fn.extend({
  superMenu: function() {
   for(var i=0,l=this.length;i<l;i++) {
    
    var elm = this.eq(i), templateId = elm.data('supermenuid');

    var pos = elm.offset(),
    elmMenuTop = $('<div class="superMenuTop">'+
     '<div class="left"></div><div class="middle"><a href="'+elm.prop('href')+'">'+elm.html()+'</a></div><div class="right"></div>'+
     '</div>'),
    elmMenuBottom = $('<div class="superMenuBottom">'+
     '<div class="left"></div><div class="leftSpacer"></div><div class="middle"></div><div class="rightSpacer"></div><div class="right"></div><div class="content">'+Novasol.Templates.parse(templateId)+'</div>'+
     '</div>');
   
    elmMenuTop.css({
     top: (pos.top-11) +'px',
     left: (pos.left-15) +'px',
     width: (elm.outerWidth()+30) +'px'
    });
   
    elmMenuBottom.css({
     top: (pos.top+29-11) +'px',
     left: (pos.left-44-19) +'px'
    });
   
    var lsw = elm.outerWidth()-2;
   
    elmMenuBottom.find('.leftSpacer').css({
     width: lsw + 'px'
    });
   
    elmMenuBottom.find('.middle').css({
     left: (64 + lsw) + 'px'
    });

    elmMenuBottom.find('.rightSpacer').css({
     left: (64 + lsw + 18) + 'px'
    });


    elm.click(onSuperMenuAnchorOver)
    .mouseover(onSuperMenuAnchorOver)
    .data('superMenuTop',elmMenuTop)
    .data('superMenuTopContent',elmMenuTop.find('.middle a'))
    .data('superMenuBottom',elmMenuBottom);

    elmMenuTop.add(elmMenuBottom).mouseover(onSuperMenuOver).mouseout(onSuperMenuOut).appendTo(document.body);
    
    
   }
   return this;
  }
 });
 
 
 Novasol.ready(function onDomReadySupermenu(){
  elmMenus = $('#menu a[data-supermenuid]').filter(function(){
    return !!document.getElementById($(this).data('supermenuid'));
 });
  elmMenus.superMenu();

  $(document.body).trigger("superMenuLoaded");
  
 });
 $(window).resize(onWindowResize);
 
})(jQuery);
/** search.js **/

if(Novasol.context === "searchresults_") {

 (function( $ ) {
 
  // Search result layout picker
  function layoutPicker( e ) {
   e.preventDefault();
   var el = $( this );
   if ( el.hasClass( 'disabled' ) ) return;
   var layout = $( this ).data( 'layout' );
   var url = location.search || "?";
   location = location.pathname+Novasol.Utils.updateQueryString( url, 'layout', layout );
  };
 
  // handle prev link in search navigation
  function prevLink( e ){
   e.preventDefault();
   if ($( this ).hasClass('disabled')) return;
   history.go(-1);
  }
 
 
 
  $( window ).load( function onWindowLoadSearch() {
  
   $('#layout-picker a').click( layoutPicker );
   $('#search-navigation a.prev' ).click( prevLink );
  });
 })( jQuery );

}
/** search-filters.js **/

if(Novasol.context === "searchresults_") {
(function( $ ) {
 
 var container, filterCategories, groupstateInput;

 // Util funciton
 function getParameterByName( url, name ){
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec( url );
  if( results == null )
   return "";
  else
   return decodeURIComponent(results[1].replace(/\+/g, " "));
 }
 
 
 // Form elements
 function submitCriteria( e ){
  var $form = $( 'form#search' ), country = $form.find("select[name=C]").val(), areas = $("select[name^='AREA']"), elmCurrentArea;
  for(var i=0,len=areas.length,elmArea;i<len;i++){
   elmArea = areas.eq(i);
   if(elmArea.val()==""){
    continue;
   }
   elmCurrentArea = elmCurrentArea || elmArea;
   if(elmCurrentArea.attr("id")<elmArea.attr("id")){
    elmCurrentArea = elmArea;
   }
  }
  if(elmCurrentArea){
   $("#R").val(elmCurrentArea.val());
  }else{
   $("#R").val("");
  }
  if($form.data("country")!=country){
   $form.attr("action","/r/"+country);
   areas.val("");
  }
  $form.submit();
 }
 
 // Date picker
 function initDatePicker(){
  // TODO: day suggestion overlay - needs theis to make his function generic
  var el = $( this ),
  img = $( '<img src="/site/redesign/img/icon_calOpen.png" alt="Selezione Data">' );
  el
  .addClass( 'datepicker-active' )
  .focus( openDatePicker )
  .after( img );
  img.click( function () {
   el.focus();
  });
 }
 
 function openDatePicker( e ){
  Novasol.calendar.create({
   target: 'input[name="SD"]',
   onSelect: submitCriteria
  });
 }
 
 // Set categorie states
 function setCategories (){
  var states = groupstateInput.val().split('-');
  for ( var i = 0, l = states.length; i < l; i++ ){
   if ( states[i] == 'c' ) filterCategories.eq(i).addClass( 'collapsed' );
  }
  setCategoryToggler( states );
 }
 
 function setCategoryToggler ( states ){
  $( '#toggle-all-categories' )[ $.inArray('c',states) != -1 ? 'addClass' : 'removeClass' ]( 'collapse-all' );
 }
 
 // Update category toggler link
 function updateCategories () {
  var states = [];
  filterCategories.each( function ( i, el ){
   states.push($( el ).is( '.collapsed' ) ? 'c' : 'e');
  });
  groupstateInput.val( states.join('-') );
  // Change label on link
  setCategoryToggler( states );
 }

 // Toggle filter category
 function toggleCategory ( e ) {
  e.preventDefault();
  var el = $( this );
  el.parent().toggleClass( 'collapsed' );
  updateCategories();
 }

 // Toggle all filter categories
 function toggleAllCategories ( e ){
  e.preventDefault();
  var anyCollapsed = filterCategories.is( '.collapsed' );
  filterCategories[ anyCollapsed ? 'removeClass' : 'addClass' ]( 'collapsed' );
  updateCategories();
 }


 // Clear a search criteria
 function clearActiveCriteria( e ){
  e && e.preventDefault();
  var key = $( this ).closest( 'span' ).data( 'key' );
  location = Novasol.Utils.updateQueryString( location.search, key, '' );
 }

 // Clear all search criteria
 function clearAllActiveCriteria( e ){
  e.preventDefault();
  url = location.search;
  $( this ).siblings( 'span' ).each( function ( i, el ){
   var key = $( el ).data( 'key' );
   url = Novasol.Utils.updateQueryString( url, key, '' );
  });
  location = url;
 }
 
 var durationSelector, initDurVal;
 
 function initDurationSelector() {
  durationSelector = $( 'select[name="DUR"]' );
  initDurVal = getParameterByName( location.search, 'DUR' );
  durationSelector
  .html(Novasol.Templates.parse('quicksearch-duration-dropdown-template',{minNights:1}))
  .change(function(e){
   if($(this).val()==""){
    e.stopPropagation();
    e.preventDefault();
    Novasol.Overlay.showHtml(615,340,Novasol.Templates.parse('quicksearch-duration-template'), onCustomDurationSelectionHide);
    $('#quicksearch-duration').delegate('a', 'click',onCustomDurationSelection); 
   }
  });
  durationSelector.val(initDurVal);
 }
 
 function onCustomDurationSelection(e) {
  e.preventDefault();
  var $this = $(this), val = $this.data('value'), txt = $this.text();
  Novasol.Overlay.hide();
  $('#custom-duration').remove();
  $('<option id="custom-duration" value="'+val+'">'+txt+'</option>')
  .insertBefore('select[name="DUR"] option[value=]');
  $('select[name="DUR"]').val(val);
  
  initDurVal = val;
  durationSelector.val( val );
  durationSelector.change();
 }
 
 function onCustomDurationSelectionHide() {
  var $sel = $('select[name="DUR"]');
  if($sel.val()=="") {
   $sel.val(initDurVal);
  }  
 }
   
 container = $( 'form#search' );
 
 if ( container.length > 0 ) {
  
  filterCategories = container.find( '.filter-category' );
  groupstateInput = $( 'input[name="groupstate"]' );

  // onDOMready fns
  $( function onDomReadyFilters() {
   setCategories();
   initDurationSelector();
   $( 'input[name="SD"]' ).each( initDatePicker );
  });

  // fns that can wait 
  $( window ).load( function onWindowLoadFilters () {
   $( 'div.active-search-criteria' ).find( 'a.functionality' ).click( clearAllActiveCriteria );
   $( 'div.filter-category' ).delegate( 'select, input', 'change', submitCriteria );
   filterCategories.find( 'a.toggler' ).click( toggleCategory );
   $( '#toggle-all-categories' ).click( toggleAllCategories );
   $( 'div.active-search-criteria' ).find( 'button' ).click( clearActiveCriteria );
  });
 }
})( jQuery );

}
/*
 * @requires InfoBox() 
 * ( http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/docs/reference.html )
 * Novasol.Favorites.getProducts()
 * returns [{
 *  productNumber:
 *  startDate:
 *  EndDate:
 * }]
 * 
 * 
 */
 
 // 
( function ( $ ) {
 var map, mapOptions, fMapBounds, propertyBox, propertyBoxDefaults, icons = {};
 
 function openPropertyBox ( e ) {
  var marker = this;
  
  var propertyBoxOptions = {
   content: marker.infoBoxContent
  };
  
  if ( propertyBox ) propertyBox.close();
  propertyBox = new InfoBox( $.extend( propertyBoxDefaults, propertyBoxOptions ) );
  propertyBox.marker = marker;
  propertyBox.open( map, marker );
 }
 
 function closePropertyBox() {
  if ( propertyBox ) {
   // only change marker's icon to viewed if not favorite
   if ( propertyBox.marker.icon != icons.favorite ) {
    propertyBox.marker.setIcon( icons.viewed );
   }
   propertyBox.close();
  }
 }
 
 function addPropertyToMap( data ) { //add a marker to map
  // position marker
  var latlng = new google.maps.LatLng( data.lat, data.lon ),
   isFav = Novasol.Favourites.isFavourite( data.propertyID, data.periodBegin, data.periodEnd );
  
  // create marker
  var marker = new google.maps.Marker({
   position: latlng,
   map: map,
   title: data.propertyID,
   icon: isFav ? icons.favorite : icons.neutral,
   shadow: icons.shadow
  });
  marker.infoBoxContent = data.content
   google.maps.event.addListener( marker, 'click', openPropertyBox );
  

  fMapBounds.extend( latlng );
  //return googMarker;
 }
 function centerMap() {
  if ( fMapBounds!= undefined ) {
   map.fitBounds( fMapBounds );
  }
  }

 function initialize() {
  
  propertyBoxDefaults = {
   disableAutoPan: false,
   maxWidth: 0,
   pixelOffset: new google.maps.Size( 11, -30 ),
   boxStyle: { 
    width: '328px'
   },
   boxClass: 'product-infoBox',
   closeBoxURL: '',
   infoBoxClearance: new google.maps.Size( 1, 1 ),
   isHidden: false,
   pane: 'floatPane',
   enableEventPropagation: false
  };

  mapOptions = {
   zoom: 12,
   maxZoom: 14,
   mapTypeControl: false,
   overviewMapControl: true,
   overviewMapControlOptions: {opened : true},
   streetViewControl: false,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
    
    map = new google.maps.Map( document.getElementById( 'search-result-map' ),
   mapOptions );
   
  icons.neutral = new google.maps.MarkerImage(
   '/site/redesign/img/houseSprite.png',
   new google.maps.Size( 21, 20 ),// marker img size
   new google.maps.Point( 0, 0 ),// origin for img ( in sprites )
   new google.maps.Point( 10, 10 )// anchor point
  );
  
  icons.viewed = new google.maps.MarkerImage(
   '/site/redesign/img/houseSprite.png',
   new google.maps.Size( 21, 20 ),// marker img size
   new google.maps.Point( 0, 20 ),// origin for img ( in sprites )
   new google.maps.Point( 10, 10 )// anchor point
  );
  
  icons.favorite = new google.maps.MarkerImage(
   '/site/redesign/img/houseSprite.png',
   new google.maps.Size( 21, 34 ),// marker img size
   new google.maps.Point( 0, 40 ),// origin for img ( in sprites )
   new google.maps.Point( 10, 24 )// anchor point
  );
  
  icons.shadow = new google.maps.MarkerImage(
   '/site/redesign/img/houseSprite.png',
   new google.maps.Size( 36, 20 ),// marker img size
   new google.maps.Point( 0, 74 ),// origin for img ( in sprites )
   new google.maps.Point( 10, 10 )// anchor point
  );
  
    
  google.maps.event.addListener( map, 'click', closePropertyBox );
  google.maps.event.addListener( map, 'zoom_changed', closePropertyBox );
    
  fMapBounds = new google.maps.LatLngBounds();

  for ( var i = 0, l = Novasol.searchResultMap.products.length; i < l; i++ ) {
   addPropertyToMap( Novasol.searchResultMap.products[ i ] );
  }
  

  var infoPanelTxt = Novasol.searchResultMap.infoPanelTxt;

  if (infoPanelTxt != "") {
   var infoPanel = document.createElement( 'DIV' );
   infoPanel.className = 'product-infoPanel low-prio-copy';
   infoPanel.innerHTML = infoPanelTxt;

   infoPanel.index = 1;
   map.controls[ google.maps.ControlPosition.TOP_RIGHT ].push( infoPanel );
  }
  
  centerMap();
 }
 
 
 $(function onDomReadySearchMap() {
 
  if ( Novasol.searchResultMap && Novasol.searchResultMap.products.length > 0 ) {
  var s = 'script',
   js = document.createElement( s ),
   e = document.getElementsByTagName( s )[0];
  js.src = "http://test.novasol.it/site/redesign/js/google.maps.infobox.js";
  js.onload = initialize;
  e.parentNode.insertBefore( js, e );
  };

});
})( jQuery );

/** house.js **/

if(Novasol.context === "showhouse_") {
 (function(window, $,undefined){
 
  var elmHouseDescription, maxDescriptionHeight = 70, dataFromNotes;
 
  function onShowHideDescriptionClick(e){
   e.preventDefault();
   elmHouseDescription = elmHouseDescription || $("#overview-tab-content .house-description");
   $(this).toggleText(function onShowText(){
    elmHouseDescription.css({
     height:maxDescriptionHeight+"px"
     });
   },function onHideText(){
    elmHouseDescription.css({
     height:"auto", 
     maxHeight: 'none'
    });
   });
  }
 
  function onPrintClick(){
   window.print();
  }
 
  function onGoToBookingClick(e) {
   e.preventDefault();
   var house = Novasol.house,
   startDate = new Date(house.availability.selectedDate),
   dur = house.calendar.settings.duration,
   endDate = new Date((new Date(startDate)).setDate(startDate.getDate() + dur)),
   adults = $("select[name=na]").val(),
   children = $("select[name=nc]").val(),
   pets = $("select[name=np]").val() || "",
   sd = Novasol.calendar.functions.formatDate(startDate),
   ed = Novasol.calendar.functions.formatDate(endDate);  
   location.href = "https://secure.novasol.com/booking.nsf/0/"
   +dataFromNotes.language
   +dataFromNotes.sitecode
   +"_bookstep1"
   +"?opendocument="
   +"&V="+house.currency
   +"&SD="+sd+"&ED="+ed
   +"&NA="+adults+"&NC="+children
   +"&H="+house.id
   +"&C="+house.country 
   +"&L="+dataFromNotes.language
   +"&COM="+dataFromNotes.sitecode
   +"&Pic01="+house.gallery.path.small.replace("http://","https://").replace("pic/146","pic/100")+house.gallery.files[0]
   +"&PR=NOSO"
   +"&U="+dataFromNotes.deployDomain
   +"&wt_si_n="+house.trackingPath;
  }
 
  function onGoToCalenderAndPricesClick(e) {
   location.hash = '#price-tab';
   $("#price-tab").triggerHandler('click');
  }
 
  $(function onDomReadyHouse(){
   if(!document.getElementById('house-top')) {
    return;
   }

   $("#house-price-box").delegate(".catalogueChange","click",function(){
    Novasol.Overlay.showHtml(200,100,$(this).siblings(".catalogueText").html());
   });
  
   $('#body').delegate('.go-to-booking','click',onGoToBookingClick)
   .delegate('.go-to-calender-and-prices','click',onGoToCalenderAndPricesClick);
  

  
   $overviewTabContent = $('#overview-tab-content');
   $houseDescription = $overviewTabContent.find('div.house-description');
   if($houseDescription.height() > maxDescriptionHeight){
    $houseDescription.css({
     height: maxDescriptionHeight+"px"
     });
    $overviewTabContent
    .find('a.showHideDescription')
    .css({
     display: 'block'
    })
    .click(onShowHideDescriptionClick);
   }
  
   $('#house-print').click(onPrintClick);
  });

  $(window).load(function onWindowLoadHouse(){
   if(!document.getElementById('house-top')) {
    return;
   }
   var house = Novasol.house;

   if (house && house.hasOwnProperty("gallery")) {
    var gallery = house.gallery;
  
    if (gallery && gallery.hasOwnProperty("path")) {
     var path = gallery.path;
            
     if (path && path.hasOwnProperty("small")) {
      Novasol.Favourites.addProductView({
       id:house.id,
       src:path.small.replace("pic/146","pic/100")+house.gallery.files[0]
      });
     }
    }
   }
  
  });
  
  Novasol.house.setDataFromNotes = function(data) {
   dataFromNotes = data;
  };

 })(this, jQuery);

}
/** house.init.js **/

if(Novasol.context === "showhouse_") {

 Novasol.house.setDataFromNotes({
  sitecode: "NOV",
  language: "380",
  deployDomain: "http://test.novasol.it"
 });
}
/** house_tabs.js **/

if(Novasol.context === "showhouse_") {
 

 (function($,undefined){
 
  function onPriceTabClick(){
   if($('#price-tab-content').length && !$('#price-tab-content').find('div.house-calendar').children("div.nosoCalendar-wrapper").length){
    var defaultSettings = Novasol.house.calendar, availability = Novasol.house.availability;
    Novasol.house.calendar = Novasol.calendar.create({
     inline:true,
     columns:2,
     target:"#price-tab-content div.house-calendar",
     months:2,
     embedMonthSelection:false,
     restricedSelection:true,
     statusRange:defaultSettings.statusRange,
     startDate:defaultSettings.startDate,
     lastDate:defaultSettings.endDate,
     duration:defaultSettings.duration,
     currentDate:defaultSettings.currentDate,
     onMonthChange:availability.updateHouseAvailability,
     onSelect:availability.loadBookingInformationForDateElm
    });
    $("#monthContainer").html(Novasol.house.calendar.getMonthDropDownHTML());
    availability.init();
    availability.load(Novasol.house.calendar);
   }
  }
 
  function onHouseTabClick(){
   var $this = $(this), tmp = $this.prop("id");

   $('#body > .tab-menu a.active, #body > .tab-content.active').removeClass("active");

   $this.add("#"+tmp+"-content").addClass("active");
  }

  $(function onDomReadyHouseTabs(){
   if(!document.getElementById('house-top')) {
    return;
   }
  
   $('#body > .tab-menu a.house-tab').click(onHouseTabClick);
   $("#price-tab").click(onPriceTabClick);
   var hash = location.href.replace(/^[^#]+/,'');
   if(hash && $(hash).length){
    onHouseTabClick.apply($(hash));
    if(hash == '#price-tab') {
     onPriceTabClick();
    }
   }
  });

 })(jQuery);
}
/** house_gallery.js **/

if(Novasol.context === "showhouse_") {
 
 (function($, undefined){
 
  var $thumbnailContainer, 
  $thumbnailBox, 
  $scrollUp, 
  $scrollDown, 
  $thumbnailControl,
  $highlights,
  $highlightsControl,
  $largeVideo;
 
  function onThumbnailControlClick(e){
   e.preventDefault();
   if(!isThumbnailsInitialized()){
    initThumbnails(); 
    $thumbnailBox.css({
     display:"block",
     opacity:0
    });
   }
   $thumbnailControl.toggleText(hideThumbGallery,showThumbGallery);
  }
 
  function setVisualScrollability() {
   var top = parseInt($thumbnailContainer.css('top'),10),
   canScrollUp = top < 0,
   canScrollDown = $thumbnailContainer.height() + top > $thumbnailContainer.parent().height();
   $scrollUp.toggleClass('can-scroll',canScrollUp);
   $scrollDown.toggleClass('can-scroll',canScrollDown);
  }
 
  function onScrollUpClick(e) {
   e.preventDefault();
   if($(this).hasClass('can-scroll')) {
    var top = parseInt($thumbnailContainer.css('top'),10),
    heightLeft = -1* top,
    scrollLength = heightLeft >= 100 ? 100 : heightLeft; 
    $thumbnailContainer.animate({
     top: "+="+scrollLength
    }, {
     duration: 150, 
     complete: setVisualScrollability
    });   
   } 
  }
 
  function onScrollDownClick(e) {
   e.preventDefault();
   if($(this).hasClass('can-scroll')) {
    var top = parseInt($thumbnailContainer.css('top'),10),
    heightLeft = $thumbnailContainer.height() + top - $thumbnailContainer.parent().height(),
    scrollLength = heightLeft >= 100 ? 100 : heightLeft; 
    $thumbnailContainer.animate({
     top: "-="+scrollLength
    }, {
     duration: 150, 
     complete: setVisualScrollability
    });  
   }
  }

  $(function onDomReadyHouseGallery(){
   if(!document.getElementById('house-top')) {
    return;
   }
  
   $thumbnailContainer = $("#thumbnail-container");
   $thumbnailBox = $('#thumbnail-box');
   $thumbnailControl = $('#thumbnail-control span');
   var $largeHouseImgBox = $('#house-top').find('div.largeHouseImage-box'), 
   $highlightsBox = $largeHouseImgBox.find('.highlights-box');
   $highlights = $highlightsBox.find('.highlights');
   $highlightsControl = $highlightsBox.find('.highlights-control').click(function(){
    $highlightsControl.toggleText();
    $highlights.toggle().removeData('auto');
   });
   $largeVideo = $largeHouseImgBox.find('.video');
  
   $("#thumbnail-control").click(onThumbnailControlClick);
  
   var $overlay = $largeHouseImgBox.find('.largeHouseImage-overlay');
   $overlay.find(".control.prevImg").click(function(){
    setLargeImageByNumber(getPrevPictureID());
   });
   $overlay.find(".control.nextImg").click(function(){
    setLargeImageByNumber(getNextPictureID());
   });
   $("#carousel-control").click(toggleCarousel);
  
   $scrollUp = $thumbnailBox.find('a.scroll-up').click(onScrollUpClick) ;
   $scrollDown = $thumbnailBox.find('a.scroll-down').click(onScrollDownClick) ;

   $thumbnailContainer.find('.video-thumbnail').click(function(){
    markActiveThumbnail(this);
    stopCarousel();
    if($largeVideo.css('visibility') == 'hidden') {
     $largeVideo.css({
      visibility: 'visible'
     });
     document.getElementById('youtube-embedded-video').playVideo();   
    }
   });


  });

  function initThumbnails(){
   var html = "", gallery = Novasol.house.gallery;
   for(var i=0,len=gallery.files.length;i<len;i++){
    html += '<div class="thumbnail'+(i?'':' active')+'" data-id="'+i+'"><img src="'+gallery.path.small+gallery.files[i]+'" alt="" /></div>';
   }
   $thumbnailContainer.append(html);
   $thumbnailContainer.delegate("#thumbnail-container .thumbnail","click",function(){
    stopCarousel();
    setLargeImageByNumber($(this).attr("data-id"));
   }); 
   $thumbnailContainer.attr("data-init","1");
  }

  function markActiveThumbnail(selector){
   $thumbnailContainer.find(".active").removeClass("active");
   $(selector, $thumbnailContainer).addClass('active');
  }

  function setLargeImageByNumber(imageNumber){
   var gallery = Novasol.house.gallery;
   Novasol.house.gallery.current = 1*imageNumber;
   $("#largeHouseImage").attr("src",gallery.path.large+gallery.files[gallery.current]);
   if(isThumbnailsInitialized()){
    markActiveThumbnail(".thumbnail[data-id='"+gallery.current+"']");
   }
   if($largeVideo.css('visibility') == 'visible') {
    $largeVideo.css({
     visibility: 'hidden'
    });
    document.getElementById('youtube-embedded-video').pauseVideo();
   }
  }
 
  function hideThumbGallery(){
   $thumbnailBox.stop(true,false).animate({
    right:"314px",
    opacity:0
   },300);
   if($highlights.data('auto')) {
    $highlights.show().removeData('auto');
    $highlightsControl.toggleText(true);   
   }
  }

  function showThumbGallery(){
   $thumbnailBox.stop(true,false).animate({
    right:"0px",
    opacity:1
   },{
    duration: 300, 
    complete: function(){
     if($thumbnailContainer.height() > $thumbnailContainer.parent().height()) {
      $scrollDown.addClass('can-scroll');
     }
    
    }
   });
   if($highlights.is(':visible')) {
    $highlights.hide().data('auto',true);
    $highlightsControl.toggleText(false);   
   }
  
  }

  function isThumbnailsInitialized(){
   return $("#thumbnail-container").attr("data-init")=="1";
  }

  function toggleCarousel(){
   var elmCarouselControl = $("#carousel-control");
   if(elmCarouselControl.hasClass("playing")){
    stopCarousel();
   }else{
    startCarousel();
   }
  }

  function stopCarousel(){
   var elmCarouselControl = $("#carousel-control");
   elmCarouselControl.removeClass("playing");
   clearTimeout(Novasol.house.gallery.timer);
  }

  function startCarousel(){
   var elmCarouselControl = $("#carousel-control");
   if(elmCarouselControl.hasClass("playing")){
    return;
   }else{
    elmCarouselControl.addClass("playing");
    playCarousel();
   }
  }

  function playCarousel(){
   var elmCarouselControl = $("#carousel-control");
   if(elmCarouselControl.hasClass("playing")){
    $(".largeHouseImage-overlay .control.nextImg").click();
    //Preload image
    var preloadImg = new Image();
    preloadImg.src = Novasol.house.gallery.path.large+Novasol.house.gallery.files[getNextPictureID()];
    Novasol.house.gallery.timer = setTimeout(playCarousel,3000);
   }
  }

  function getNextPictureID(){
   if(Novasol.house.gallery.current==Novasol.house.gallery.files.length-1){
    return 0;
   }else{
    return Novasol.house.gallery.current+1;
   }
  }

  function getPrevPictureID(){
   if(Novasol.house.gallery.current==0){
    return Novasol.house.gallery.files.length-1;
   }else{
    return Novasol.house.gallery.current-1;
   }
  }


 })(jQuery);

}
/** house_availability.js **/

if(Novasol.context === "showhouse_") {
 (function($,undefined){
 
  var $housePeriods,$houseOffers,selectedPeriodId, dataFromNotes;
 
  Novasol.house = Novasol.house || {};
  Novasol.house.availability = {
   load : loadAvailabilityForCalendar,
   rowTemplate : "<tr id=\"%id%\"class=\"%class%\" style=\"%style%\"><td>%sd%</td><td>%ed%</td><td>%dur% [nights]</td><td>%before%</td><td>%price%</td></tr>",
   conceptTemplate : "<div class=\"nosoCalendar-concept\"><img src=\"%src%\" alt=\"%alt%\" title=\"%title%\" /></div>",
   rows : 0,
   rowOffset : 0,
   rowsToShow : 7,
   arrivalDates : [],
   updateHouseAvailability : updateHouseAvailability,
   init : initAvailability,
   loadBookingInformationForDateElm : loadBookingInformationForDateElm,
   cachedRequests : [],
   bookingInformationBoxData : {},
   selectedDate : null,
   showOffers : showOffers,
   setDataFromNotes: setDataFromNotes
  };
  
  function setDataFromNotes(data){
   dataFromNotes = data;
  }
  
  function initAvailability(){
   $housePeriods = $('#house-periods');
   $houseOffers = $('#house-offers');
   $('#price-tab-content')
   .find("select[name='na'],select[name='nc'],select[name='np'],select[name='ni']")
   .change(updateWithGuestsAndPeriods)
   .end()
   .find('select[name="DUR"]')
   .html(Novasol.Templates.parse('quicksearch-duration-dropdown-template',{minNights:Novasol.house.minNights||1}))
   .val(Novasol.house.calendar.settings.duration)
   .change(onDurationChange);
  
   var startDateInMillis = Novasol.house.startDateInMillis;
   if(startDateInMillis){
    Novasol.house.availability.selectedDate = new Date(startDateInMillis);
   }
  
   $("#house-seasons-link").delegate("a","click",function(){
    var elmLink = $(this);
    if(elmLink.html()==elmLink.attr("data-show")){
     elmLink.html(elmLink.attr("data-hide"));
     $("#"+Novasol.house.calendar.settings.name).addClass("nosoCalendar-show-seasonCodes");
    }else{
     elmLink.html(elmLink.attr("data-show"));
     $("#"+Novasol.house.calendar.settings.name).removeClass("nosoCalendar-show-seasonCodes");
    }
    return false;
   });
   var elmBookingInformation = $("#house-bookingInformation"),
   offset = elmBookingInformation.offset();
   Novasol.house.availability.bookingInformationBoxData = {
    baseOffset:offset,
    elm:elmBookingInformation
   };
   $(window).scroll(updateBookingInformationPosition);
   $(window).resize(updateBookingInformationPosition);
 
   $('#price-tab-content table.period-table th span').click(sortPeriodTable);
 
   $("#next-period-rows").click(goToNextOffset);
   $("#prev-period-rows").click(goToPrevOffset);
   $housePeriods
   .delegate("tr","mouseenter",function(){
    var $this = $(this).addClass("hover");
    Novasol.house.calendar.hoverIn($("#"+Novasol.house.calendar.settings.name+"-"+$this.data("id")));
   })
   .delegate("tr","mouseleave",function(){
    var $this = $(this).removeClass("hover");
    Novasol.house.calendar.hoverOut($("#"+Novasol.house.calendar.settings.name+"-"+$this.data("id")));
   })
   .delegate("tr","click",function(){
    Novasol.house.availability.loadBookingInformationForDateElm(null,new Date(1*$(this).data("id")));
   });
  
   $houseOffers
   .delegate("tr","mouseenter",function(){
    var $this = $(this).addClass("hover");
    Novasol.house.calendar.hoverIn($("#"+Novasol.house.calendar.settings.name+"-"+$this.data("id")),$this.data('duration'));
   })
   .delegate("tr","mouseleave",function(){
    var $this = $(this).removeClass("hover");
    Novasol.house.calendar.hoverOut($("#"+Novasol.house.calendar.settings.name+"-"+$this.data("id")),$this.data('duration'));
   })
   .delegate("tr","click",function(){
    $('select[name=dur]').val($(this).data("duration"));
    updateWithGuestsAndPeriods();   
   });
  
  
  
   $("#"+Novasol.house.calendar.settings.name)
   .delegate(".nosoCalendar-date.selectable","mouseenter",function(){
    var data = Novasol.calendar.functions.extractDataFromId($(this).attr("id"));
    $("#period-row-"+data.date.getTime()).addClass("hover");
   })
   .delegate(".nosoCalendar-date.selectable","mouseleave",function(){
    var data = Novasol.calendar.functions.extractDataFromId($(this).attr("id"));
    $("#period-row-"+data.date.getTime()).removeClass("hover");
   });
 
  }
 
  function onCustomDurationSelection(e) {
   e.preventDefault();
   var $this = $(this), val = $this.data('value'), txt = $this.text();
   Novasol.Overlay.hide();
   $('#custom-duration').remove();
   $('<option id="custom-duration" value="'+val+'">'+txt+'</option>')
   .insertBefore('select[name="DUR"] option[value=]');
   $('select[name="DUR"]').val(val);
  
   updateWithGuestsAndPeriods();
  }
 
  function onCustomDurationSelectionHide() {
   var $sel = $('select[name="DUR"]');
   if(!$sel.val()) {
    $sel.val(Novasol.house.calendar.settings.duration);
   }  
  }
 
 
  function onDurationChange() {
   if($(this).val()) {
    updateWithGuestsAndPeriods();
   }
   else {
    Novasol.Overlay.showHtml(615,340,Novasol.Templates.parse('duration-overlay-template'), onCustomDurationSelectionHide);
    $('#quicksearch-duration').delegate('a', 'click',onCustomDurationSelection);   
   }
  }
 
  function loadAvailabilityForCalendar(calendar){
   var people = 1*$("select[name='na']").val() + 1*$("select[name='nc']").val(),
   duration = $("select[name='DUR']").val(),
   startDate = new Date(calendar.settings.currentDate),
   startDateString,
   endDate = null,
   endDateString,
   reload = Novasol.house.numberOfCalendars>1,
   params,
   now = new Date(),
   ajaxData;
  
   calendar.settings.duration = 1*duration;
   startDate.setDate(1);
   endDate = new Date(startDate);
   endDate.setMonth(endDate.getMonth()+calendar.settings.months);
   endDate.setDate(endDate.getDate()-1);
   if(startDate<now){
    startDate = now;
   }
   if(startDate<calendar.settings.currentDate){
    startDate = new Date(calendar.settings.currentDate);
   }
   startDateString = Novasol.calendar.functions.formatDate(startDate);
   endDateString = Novasol.calendar.functions.formatDate(endDate);  
  
   params = {
    com:dataFromNotes.sitecode,
    l:dataFromNotes.language,
    h:Novasol.house.id,
    season:startDate.getFullYear(),
    na:people,
    dur:duration,
    sd:startDateString,
    ed:endDateString,
    reload:reload
   };
  
   $housePeriods.html("");
   $('#'+Novasol.house.calendar.settings.name+' .nosoCalendar-month .nosoCalendar-concepts').remove();
   ajaxData = Novasol.house.availability.cachedRequests[startDateString];
   if(ajaxData==null){
    $.getJSON(dataFromNotes.houseAvailabilityPath, params, processAjaxData);
   }else{
    processAjaxData(ajaxData);
   }
  }
 
  function processAjaxData(ajaxData){
   var settings = Novasol.house.calendar.settings;
   var redraw = false;
   Novasol.house.availability.cachedRequests[ajaxData.id] = ajaxData;
   if(ajaxData.calendar && !$.isEmptyObject(ajaxData.calendar)){
    settings.statusRange = ajaxData.calendar;
    redraw = true;
   }
   if(ajaxData.seasonCodes && ajaxData.seasonCodes.length>0){
    settings.seasonCodes = ajaxData.seasonCodes;
    redraw = true;
   }
   if(redraw){
    Novasol.house.calendar.redraw(settings);
   }
   markArrivalDates(ajaxData.periods);
   setPeriods(ajaxData.periods);
   setConcepts(ajaxData.conceptPeriods);
   if(Novasol.house.availability.selectedDate){
    loadBookingInformationForDateElm(null, Novasol.house.availability.selectedDate);
   }
  }
 
  function updateHouseAvailability(){
   Novasol.house.availability.load(Novasol.house.calendar);
  }
 
  function setCalendarStatuses(ajaxData){
   if(ajaxData != null && ajaxData.length>0){
    Novasol.house.calendar.settings.statusRange = ajaxData;
    Novasol.house.calendar.redraw(Novasol.house.calendar.settings);
   }
  }
 
  function sortPeriodTable(e) {
   var $this = $(this), 
   sortProp = $this.data('sort-property'),
   direction = 1;

   if($this.hasClass('asc')) {
    $this.removeClass('asc').addClass('desc');
    direction = -1;
   }
   else {
    $this.removeClass('desc').addClass('asc');
   }
   $this.parent().siblings().find('.asc, .desc').removeClass('asc desc');
  
   var $table = $(this).closest('table');
   $table.data('periodsCache').sort(function(a,b){
    var sa = a[sortProp], sb = b[sortProp];
    return sa == sb ? 0 : sa > sb ? 1 * direction : -1 * direction;
   });
   $table.data('render')(); 
  }
 
  function renderPeriods() {
   var av = Novasol.house.availability;
   var html = Novasol.Templates.parse('period-table-template', {
    periods: $housePeriods.parent().data('periodsCache').slice(av.rowOffset,av.rowOffset+av.rowsToShow),
    type: 'period-row'
   });
   $housePeriods.html(html);
   $(selectedPeriodId).addClass('selected');
  }
 
  function setPeriods(periods){
   var av = Novasol.house.availability, cachedPeriods = periods.slice(0);
   $housePeriods.parent()
   .data('periodsCache',cachedPeriods)
   .data('render',renderPeriods);
   renderPeriods();
   var showNext = cachedPeriods.length > av.rowOffset+av.rowsToShow;
   $("#next-period-rows").toggle(showNext);
  }
 
  function goToNextOffset(e){
   e.preventDefault();
   var av = Novasol.house.availability;
   av.rowOffset += av.rowsToShow;
   renderPeriods();
   var showNext = $housePeriods.parent().data('periodsCache').length > av.rowOffset+av.rowsToShow;
   $("#next-period-rows").toggle(showNext);
   $("#prev-period-rows").show();
  
  }
 
  function goToPrevOffset(e){
   e.preventDefault();
   var av = Novasol.house.availability;
   av.rowOffset = av.rowOffset <= av.rowsToShow ? 0 : av.rowOffset -av.rowsToShow;
   renderPeriods();
   $("#prev-period-rows").toggle(av.rowOffset>0);
   $("#next-period-rows").show();
  }

 
  function renderOffers() {
   var html = Novasol.Templates.parse('period-table-template', {
    periods: $houseOffers.parent().data('periodsCache'),
    type: 'house-offer'
   });
   $houseOffers.html(html);
   $(selectedPeriodId).addClass('selected');
  }
 
  function showOffers(periods){
   var cachedPeriods = periods.slice(0);
   if(periods.length > 0){
    $houseOffers.parent()
    .data('periodsCache',cachedPeriods)
    .data('render',renderOffers);
    renderOffers();
    $("#house-offers-wrapper").show().yellowFade();
   }
   else{
    $("#house-offers-wrapper").hide();
   }
  } 
 
  function setConcepts(conceptPeriods){
   var html = "", elmMonth,concepts;
   for(var key in conceptPeriods){
    concepts = conceptPeriods[key];
    for(var x in concepts){
     html += Novasol.house.availability.conceptTemplate
     .replace(/%src%/ig,concepts[x].img)
     .replace(/%alt%/ig,concepts[x].name)
     .replace(/%title%/ig,concepts[x].name);
    }
    elmMonth = $("#"+Novasol.house.calendar.settings.name+"-"+key).closest(".nosoCalendar-month");
    elmMonth.remove(".nosoCalendar-concepts");
    elmMonth.append("<div class=\"nosoCalendar-concepts\">"+html+"</div>");
   }
  }
 
 

 
  function markArrivalDates(periods){
   var id= "#"+Novasol.house.calendar.settings.name, ids=[];
   $(id+' .selectable').removeClass("selectable");
   for (var i=0,period;period=periods[i];i++) {
    ids[ids.length] = id+"-"+period.sd;
   }
   $(ids.join(',')).addClass("selectable");
  }
 
  function loadBookingInformationForDateElm(elmDate,date){
   var cachedPeriods = $housePeriods.parent().data('periodsCache'),ts = date.getTime();
   for(var i=0,period;period = cachedPeriods[i];i++) {
    if(period.sd == ts) {
     var $loading = $('<div class="loading-overlay"><img src="/site/redesign/img/loading.gif"/></div>').appendTo('#house-offers-wrapper, #house-bookingInformation');
     var params = {
      "dur":Novasol.house.calendar.settings.duration,
      "na":$("select[name='na']").val(),
      "nc":$("select[name='nc']").val(),
      "ni":$("select[name='ni']").val(),
      "np":$("select[name='np']").val(),
      "s":Novasol.house.season,
      "com":dataFromNotes.sitecode,
      "l":dataFromNotes.language,
      "h":Novasol.house.id,
      "sd":Novasol.calendar.functions.formatDate(date)
     };
     Novasol.house.calendar.markDatesAsSelected(date,Novasol.house.calendar.settings.duration);
     markPeriodAsSelected(date);
     updateFavDates(date);
     Novasol.house.availability.selectedDate = new Date(date);
     $.post(dataFromNotes.bookingInformationPath,params,function(reply){
      var elm = $("#house-bookingInformation");
      elm.html(reply);
      updateBookingInformationPosition();
      $loading.remove();
     },"text");
     return;   
    }
   }
  }

  function updateFavDates(date) {
   var edDate = new Date(date.getTime()+Novasol.house.calendar.settings.duration*1000*60*60*24); 
   $('#house-top var.fav-icon')
   .data('start',date.getDate() + '-'+ (date.getMonth()+1)+'-'+date.getYear())
   .data('end',edDate.getDate() + '-'+ (edDate.getMonth()+1)+'-'+edDate.getYear());
  }
 
  function markPeriodAsSelected(date){
   $(".period-row").removeClass("selected");
   selectedPeriodId = null;
   if(date){
    selectedPeriodId = "#period-row-"+date.getTime();
    $(selectedPeriodId).addClass("selected");
   }
  }
 
  function updateWithGuestsAndPeriods(){
   var adults, children, elmBookingInformationParent;
   adults = 1*$("select[name='na']").val();
   children = 1*$("select[name='nc']").val();
  
   if(adults>1*Novasol.house.capacity.na+1*Novasol.house.capacity.extraBeds || 
    adults+children>1*Novasol.house.capacity.na+1*Novasol.house.capacity.nc+1*Novasol.house.capacity.extraBeds){
   
    $("#house-capacity-message").show().yellowFade();
   }else{
    $("#house-capacity-message").hide();
    Novasol.house.availability.cachedRequests = [];
    markPeriodAsSelected(null);
    Novasol.house.calendar.markDatesAsSelected(null,-1);
    Novasol.house.availability.updateHouseAvailability();
    elmBookingInformationParent = $("#house-bookingInformation");
    elmBookingInformationParent.html(elmBookingInformationParent.attr("data-text"));
    if(Novasol.house.availability.selectedDate){
     $("#period-row-"+Novasol.house.availability.selectedDate.getTime()).click();
    }
   }
  }
 
  function updateBookingInformationPosition(){
   if(!$('#price-tab-content').hasClass('active') || $('html').hasClass('ie7')){
    return;
   }
   var elmBookingInformation = Novasol.house.availability.bookingInformationBoxData.elm,
   elmBookingInformationParent = elmBookingInformation.parent(),
   maxHeight;
   elmBookingInformation.css({
    "position":"absolute",
    "top":"0px",
    "left":"0px",
    "bottom":"auto"
   });
   elmBookingInformationParent.css("height","0px");
   maxHeight = elmBookingInformationParent.parent().height()-(elmBookingInformationParent.innerHeight()-elmBookingInformationParent.height());
   elmBookingInformationParent.css("height",maxHeight+"px");
   if($(window).height()>elmBookingInformation.height()){
    var baseOffset = Novasol.house.availability.bookingInformationBoxData.baseOffset,
    offset = elmBookingInformation.offset(),
    documentScrollTop = $(document).scrollTop();
    if((elmBookingInformation.innerHeight() + documentScrollTop - baseOffset.top) >= elmBookingInformationParent.height()){
     elmBookingInformation.css({
      position:"absolute",
      left:0,
      top:"auto",
      bottom:0
     });
    }else if(offset.top<documentScrollTop || offset.top>baseOffset.top){
     elmBookingInformation.css({
      position:"fixed",
      left:offset.left,
      top:0,
      bottom:"auto"
     });
    }
   }
  }
 
 })(jQuery);

}
/** house_availability.init.js **/
if(Novasol.context === "showhouse_") {
 Novasol.house.availability.setDataFromNotes({
  sitecode: "NOV",
  language: "380",
  houseAvailabilityPath: "/HouseAvailability",
  bookingInformationPath:"/BookingInformation" 
 });
}
/** house_map.js **/

if(Novasol.context === "showhouse_") {
 (function($, undefined){
 
  var map;
 
  function init() {
   if(map) {
    return;
   }
   var elmMapContent = $("#map-tab-content"), 
   elmGoogleMapDiv = elmMapContent.find(".house-googleMap");

   var ll = new google.maps.LatLng(elmGoogleMapDiv.attr("data-lat"), elmGoogleMapDiv.attr("data-long"));
   var mapOptions = {
    center: ll,
    zoom: 8,
    maxZoom: 11,
    minZoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   map = new google.maps.Map(elmGoogleMapDiv.get(0),mapOptions);

   if(elmMapContent.hasClass('load-in-background')) {
    google.maps.event.addListener(map, 'tilesloaded', function(){
     elmMapContent.removeClass('load-in-background');
    }); 
   }

   var marker = new google.maps.Marker({
    position: ll, 
    map: map, 
    title: elmGoogleMapDiv.attr("data-title"),
    icon: "/site/nov/_img/icons/mapicons/mapHouse.png"
   });  
  }
 
 
  function loadGoogleMap() {
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=Novasol.house.map.init";
   document.body.appendChild(script);
  } 
 
  $(function onDomReadyHouseMap(){
   if(!document.getElementById('house-top')) {
    return;
   }

   if(location.href.indexOf('#map-tab') != -1) {
    loadGoogleMap();
   }  
  
   $("#map-tab").click(function(){
    google.maps.event.trigger(map, 'resize');
   });    

   $(".map-box a").click(function(){
    $("#map-tab").click();
   });
  });



  $(window).load(function onWindowLoadHouseMap(){
   if(!document.getElementById('house-top')) {
    return;
   }
  
   if(location.href.indexOf('#map-tab') == -1) {
    $("#map-tab-content").addClass('load-in-background');
    loadGoogleMap();
   }
   else {
    $("#map-tab").click();
   }
  
  });

  Novasol.house = Novasol.house || {};
  Novasol.house.map = {
   init: init
  };


 })(jQuery);
}
/** house_send_to_friend.js **/

if(Novasol.context === "showhouse_") {

 ( function ( $ ) {
  var form, feedback, dataFromNotes;
   
  function sendToFriend() {
   var el = $( '#email-overlay' ),
   html = el.text(),
   w = el.data().width,
   h = el.data().height;
   
   Novasol.Overlay.showHtml( w, h, html );
  
   form = $( 'form.email-overlay' );
   feedback = form.siblings( '.feedback' );
  
   form.bind( 'validation-success', submitSendToFriend );
  }
 
  function submitSendToFriend() {
   $.ajax({
    url: dataFromNotes.sendToFriendPath,
    data: $( this ).serialize(),
    dataType: 'text',
    type: 'POST',
    success: submitSuccess,
    error: showError
   });
  }
 
  function submitSuccess( d, ts, jqx ) {
   if ( d == 'success' ){
    showSuccess();
   } else {
    showError();
   }
  }
 
  function showError(){
   feedback
   .removeClass( 'success' )
   .addClass( 'error' )
   .yellowFade();
  }
 
  function showSuccess(){
   feedback
   .removeClass( 'error' )
   .addClass( 'success' )
   .yellowFade();
   
   setTimeout( Novasol.Overlay.hide, 2000 );
  }
 
  // no rush
  $( window ).load( function onWindowLoadHouseSendToFriend() {
   if(!document.getElementById('house-top')) {
    return;
   }
  
   $( '#house-top div.house-social div.social' )
   .find( 'a.sendToFriend' ).click( sendToFriend );
  });
  
  Novasol.house.SendToFriend = {
   setDataFromNotes: function(data) { dataFromNotes=data}
  };
 
 })( jQuery );
}
/** house_send_to_friend.init.js **/

if(Novasol.context === "showhouse_") {
 Novasol.house.SendToFriend.setDataFromNotes({
  sendToFriendPath: "/SendToFriend"
 });
}

/** social-links-scripts.js **/
( function ( $ ) {
 function activateLinks () {
  /* FACEBOOK LIKE */
  if ( $( '.fb-like' ).length > 0 ) {
   (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s);js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
    js.onload = attachListener;
    fjs.parentNode.insertBefore(js, fjs);

    function attachListener() {
     FB.Event.subscribe('edge.create',
      function(response) {
        dcsMultiTrack('DCS.dcsuri','/HousePresentation_SocialMediaShare','WT.ti','HousePresentation_SocialMediaShare','DCSext.socialtype', 'Like', 'DCSext.socialmedia','Facebook','DCSext.socialmessage','Boedha HFR003 Blesdyke_HFR_528','WT.dl','24','wt.cg_n', '','wt.cg_s', '','wt.si_p', '','wt.si_n', '', 'wt.ti', '', 'WT.pn_sku', '', 'WT.tx_e', '');
     });
    }
   }(document, 'script', 'facebook-jssdk'));
  }

  /* GOOGLE +1 */
  if ( $( '.g-plusone' ).length > 0 ) {
   function gPlusTracker() {
    dcsMultiTrack('DCS.dcsuri','/HousePresentation_SocialMediaShare','WT.ti','HousePresentation_SocialMediaShare','DCSext.socialtype', 'Share', 'DCSext.socialmedia','GooglePlus','DCSext.socialmessage','Boedha HFR003 Blesdyke_HFR_528','WT.dl','24','wt.cg_n', '','wt.cg_s', '','wt.si_p', '','wt.si_n', '', 'wt.ti', '', 'WT.pn_sku', '', 'WT.tx_e', '');
   }
   window.___gcfg = {lang: 'en-GB'};

   (function() {
    var po = document.createElement('script');po.type = 'text/javascript';po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(po, s);
   })();
  }

  /* TWITTER FOLLOW */
  if ( $( '.twitter-follow-button' ).length > 0 ) {
   (function() {
    var sc = document.createElement('script');sc.type = 'text/javascript';
    sc.src = '//platform.twitter.com/widgets.js';
    var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(sc, s);
   })();
  }
 }



 function openSocialOverlay() {
  var html = $( '#social-overlay-tmpl' ).html().replace(/^\s*<!--|-->\s*$/g,'');
  Novasol.Overlay.showHtml( 220, 220, html );
  activateLinks();
 }
 $( window ).load( function onWindowLoadSocialLinksScripts() {
  $( '.moreSocial' ).click( openSocialOverlay );
 });
 
})( jQuery );
(function($,undefined){

 var oldWrite;

 function ourWrite(str) {
  $('#chat-link-container span').click(new Function('event',$(str).attr('onclick')));
  $(document.body).append('<div style="display: none;" id="actual-chat-link">'+str+'</div>');
  document.write = oldWrite;
 }
 
 $(window).load(function onWindowLoadChat(){
  setTimeout(function(){
   oldWrite = document.write;
   document.write = ourWrite;
   $(document.body).append('<script src="//chatserver.comm100.com/js/LiveChat.js?siteId=58057&amp;planId=2559&amp;partnerId=-1" type="text/javascript"></script><script type="text/javascript" src="//chatserver.comm100.com/ChatButton.aspx?siteId=58057&amp;planId=2559&amp;partnerId=-1"></script>');
  },10);
 });
 
})(jQuery);
/** webtrends.js **/

// WebTrends SmartSource Data Collector Tag
// Version: 8.6.2     
// Tag Builder Version: 3.0
// Created: 5/11/2010 1:54:51 PM
// Optimized and refactored to allow lazyloading, mbj 2011-11-07

(function($, undefined) {
 
 var dataFromNotes;


 function WebTrends(dcsidStr){
  var that=this;
  // begin: user modifiable
  this.dcsid=dcsidStr;
  this.domain="stat.novasol.com";
  this.timezone=1;
  var splitarray = new Array();
  splitarray = location.host.split(".");
  var splitdomain = "."+splitarray[splitarray.length-2]+"."+splitarray[splitarray.length-1]
  if (splitdomain.toLowerCase() == ".co.uk") {
   splitdomain = "."+splitarray[splitarray.length-3]+splitdomain;
  }
  this.fpcdom=splitdomain;
  this.onsitedoms="";
  this.downloadtypes="arc,arj,ashx,avi,bin,csv,dll,doc,docx,exe,gz,hqx,mov,mp2,mp3,mp4,mpeg,mpg,pdf,pps,ppsx,ppt,pptx,rar,rpm,sit,svg,swf,tar,txt,wav,wmv,xls,xlsx,z,zip";
  this.navigationtag="div,table";
  this.adclickparam="WT.ac";
  this.trackevents=true;
  this.trimoffsiteparams=true;
  this.enabled=true;
  this.i18n=false;
  this.fpc="WT_FPC";
  this.paidsearchparams="gclid";
  // end: user modifiable
  this.DCS={};
  this.WT={};
  this.DCSext={};
  this.images=[];
  this.index=0;
  this.exre=(function(){
   return(window.RegExp?new RegExp("dcs(uri)|(ref)|(aut)|(met)|(sta)|(sip)|(pro)|(byt)|(dat)|(p3p)|(cfg)|(redirect)|(cip)","i"):"");
  })();
  this.re=(function(){
   return(window.RegExp?(that.i18n?{
    "%25":/\%/g
   }:{
    "%09":/\t/g,
    "%20":/ /g,
    "%23":/\#/g,
    "%26":/\&/g,
    "%2B":/\+/g,
    "%3F":/\?/g,
    "%5C":/\\/g,
    "%22":/\"/g,
    "%7F":/\x7F/g,
    "%A0":/\xA0/g
   }):"");
  })();
 }
 WebTrends.prototype.dcsGetId=function(callback){
  if (this.enabled&&(document.cookie.indexOf(this.fpc+"=")==-1)&&(document.cookie.indexOf("WTLOPTOUT=")==-1)){
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.onload = callback;
   script.src = "http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+this.domain+"/"+this.dcsid+"/wtid.js";
   document.body.appendChild(script);
  }
  else {
   callback();
  }
 }
 WebTrends.prototype.dcsGetCookie=function(name){
  var cookies=document.cookie.split("; ");
  var cmatch=[];
  var idx=0;
  var i=0;
  var namelen=name.length;
  var clen=cookies.length;
  for (i=0;i<clen;i++){
   var c=cookies[i];
   if ((c.substring(0,namelen+1))==(name+"=")){
    cmatch[idx++]=c;
   }
  }
  var cmatchCount=cmatch.length;
  if (cmatchCount>0){
   idx=0;
   if ((cmatchCount>1)&&(name==this.fpc)){
    var dLatest=new Date(0);
    for (i=0;i<cmatchCount;i++){
     var lv=parseInt(this.dcsGetCrumb(cmatch[i],"lv"));
     var dLst=new Date(lv);
     if (dLst>dLatest){
      dLatest.setTime(dLst.getTime());
      idx=i;
     }
    }
   }
   return unescape(cmatch[idx].substring(namelen+1));
  }
  else{
   return null;
  }
 }
 WebTrends.prototype.dcsGetCrumb=function(cval,crumb,sep){
  var aCookie=cval.split(sep||":");
  for (var i=0;i<aCookie.length;i++){
   var aCrumb=aCookie[i].split("=");
   if (crumb==aCrumb[0]){
    return aCrumb[1];
   }
  }
  return null;
 }
 WebTrends.prototype.dcsGetIdCrumb=function(cval,crumb){
  var id=cval.substring(0,cval.indexOf(":lv="));
  var aCrumb=id.split("=");
  for (var i=0;i<aCrumb.length;i++){
   if (crumb==aCrumb[0]){
    return aCrumb[1];
   }
  }
  return null;
 }
 WebTrends.prototype.dcsIsFpcSet=function(name,id,lv,ss){
  var c=this.dcsGetCookie(name);
  if (c){
   return ((id==this.dcsGetIdCrumb(c,"id"))&&(lv==this.dcsGetCrumb(c,"lv"))&&(ss==this.dcsGetCrumb(c,"ss")))?0:3;
  }
  return 2;
 }
 WebTrends.prototype.dcsFPC=function(){
  if (document.cookie.indexOf("WTLOPTOUT=")!=-1){
   return;
  }
  var WT=this.WT;
  var name=this.fpc;
  var dCur=new Date();
  var adj=(dCur.getTimezoneOffset()*60000)+(this.timezone*3600000);
  dCur.setTime(dCur.getTime()+adj);
  var dExp=new Date(dCur.getTime()+315360000000);
  var dSes=new Date(dCur.getTime());
  WT.co_f=WT.vtid=WT.vtvs=WT.vt_f=WT.vt_f_a=WT.vt_f_s=WT.vt_f_d=WT.vt_f_tlh=WT.vt_f_tlv="";
  if (document.cookie.indexOf(name+"=")==-1){
   if ((typeof(gWtId)!="undefined")&&(gWtId!="")){
    WT.co_f=gWtId;
   }
   else if ((typeof(gTempWtId)!="undefined")&&(gTempWtId!="")){
    WT.co_f=gTempWtId;
    WT.vt_f="1";
   }
   else{
    WT.co_f="2";
    var curt=dCur.getTime().toString();
    for (var i=2;i<=(32-curt.length);i++){
     WT.co_f+=Math.floor(Math.random()*16.0).toString(16);
    }
    WT.co_f+=curt;
    WT.vt_f="1";
   }
   if (typeof(gWtAccountRollup)=="undefined"){
    WT.vt_f_a="1";
   }
   WT.vt_f_s=WT.vt_f_d="1";
   WT.vt_f_tlh=WT.vt_f_tlv="0";
  }
  else{
   var c=this.dcsGetCookie(name);
   var id=this.dcsGetIdCrumb(c,"id");
   var lv=parseInt(this.dcsGetCrumb(c,"lv"));
   var ss=parseInt(this.dcsGetCrumb(c,"ss"));
   if ((id==null)||(id=="null")||isNaN(lv)||isNaN(ss)){
    return;
   }
   WT.co_f=id;
   var dLst=new Date(lv);
   WT.vt_f_tlh=Math.floor((dLst.getTime()-adj)/1000);
   dSes.setTime(ss);
   if ((dCur.getTime()>(dLst.getTime()+1800000))||(dCur.getTime()>(dSes.getTime()+28800000))){
    WT.vt_f_tlv=Math.floor((dSes.getTime()-adj)/1000);
    dSes.setTime(dCur.getTime());
    WT.vt_f_s="1";
   }
   if ((dCur.getDay()!=dLst.getDay())||(dCur.getMonth()!=dLst.getMonth())||(dCur.getYear()!=dLst.getYear())){
    WT.vt_f_d="1";
   }
  }
  WT.co_f=escape(WT.co_f);
  WT.vtid=(typeof(this.vtid)=="undefined")?WT.co_f:(this.vtid||"");
  WT.vtvs=(dSes.getTime()-adj).toString();
  var expiry="; expires="+dExp.toGMTString();
  var cur=dCur.getTime().toString();
  var ses=dSes.getTime().toString();
  document.cookie=name+"="+"id="+WT.co_f+":lv="+cur+":ss="+ses+expiry+"; path=/"+(((this.fpcdom!=""))?("; domain="+this.fpcdom):(""));
  var rc=this.dcsIsFpcSet(name,WT.co_f,cur,ses);
  if (rc!=0){
   WT.co_f=WT.vtvs=WT.vt_f_s=WT.vt_f_d=WT.vt_f_tlh=WT.vt_f_tlv="";
   if (typeof(this.vtid)=="undefined"){
    WT.vtid="";
   }
   WT.vt_f=WT.vt_f_a=rc;
  }
 }
 // Code section for Generate an Ad View query parameter for every Ad Click link.
 WebTrends.prototype.dcsAdSearch=function(){
  if (document.links){
   var param=this.adclickparam+"=";
   var paramlen=param.length;
   var paramre=new RegExp(param,"i");
   var len=document.links.length;
   var pos=end=-1;
   var anch=urlp=value="";
   var urlpre;
   var url=document.URL+"";
   var start=url.search(paramre);
   if (start!=-1){
    end=url.indexOf("&",start);
    urlp=url.substring(start,(end!=-1)?end:url.length);
    urlpre=new RegExp(urlp+"(&|#)","i");
   }
   for (var i=0;i<len;i++){
    if (document.links[i].href){
     anch=document.links[i].href+"";
     if (urlp.length>0){
      anch=anch.replace(urlpre,"$1");
     }
     pos=anch.search(paramre);
     if (pos!=-1){
      start=pos+paramlen;
      end=anch.indexOf("&",start);
      value=anch.substring(start,(end!=-1)?end:anch.length);
      this.WT.ad=this.WT.ad?(this.WT.ad+";"+value):value;
     }
    }
   }
  }
 }
 WebTrends.prototype.dcsIsOnsite=function(host){
  if (host.length>0){
   host=host.toLowerCase();
   if (host==window.location.hostname.toLowerCase()){
    return true;
   }
   if (typeof(this.onsitedoms.test)=="function"){
    return this.onsitedoms.test(host);
   }
   else if (this.onsitedoms.length>0){
    var doms=this.dcsSplit(this.onsitedoms);
    var len=doms.length;
    for (var i=0;i<len;i++){
     if (host==doms[i]){
      return true;
     }
    }
   }
  }
  return false;
 }
 WebTrends.prototype.dcsTypeMatch=function(pth, typelist){
  var type=pth.toLowerCase().substring(pth.lastIndexOf(".")+1,pth.length);
  var types=this.dcsSplit(typelist);
  var tlen=types.length; 
  for (var i=0;i<tlen;i++){
   if (type==types[i]){
    return true;
   }
  }
  return false;
 }
 WebTrends.prototype.dcsEvt=function(evt,tag){
  var e=evt.target||evt.srcElement;
  while (e.tagName&&(e.tagName.toLowerCase()!=tag.toLowerCase())){
   e=e.parentElement||e.parentNode;
  }
  return e;
 }
 WebTrends.prototype.dcsNavigation=function(evt){
  var id="";
  var cname="";
  var elems=this.dcsSplit(this.navigationtag);
  var elen=elems.length; 
  var i,e,elem;
  for (i=0;i<elen;i++){
   elem=elems[i];
   if (elem.length){
    e=this.dcsEvt(evt,elem);
    id=(e.getAttribute&&e.getAttribute("id"))?e.getAttribute("id"):"";
    cname=e.className||"";
    if (id.length||cname.length){
     break;
    }
   }
  }
  return id.length?id:cname;
 }
 WebTrends.prototype.dcsBind=function(event,func){
  if ((typeof(func)=="function")&&document.body){
   if (document.body.addEventListener){
    document.body.addEventListener(event, function(fn,t){
     return function(){
      fn.apply(t,arguments);
     }
    }(func,this), true);
  }
  else if(document.body.attachEvent){
   document.body.attachEvent("on"+event, function(fn,t){
    return function(){
     fn.apply(t,arguments);
    }
   }(func,this));
 }
}
}
WebTrends.prototype.dcsET=function(){
 var e=(navigator.appVersion.indexOf("MSIE")!=-1)?"click":"mousedown";
 this.dcsBind(e,this.dcsDownload);
 this.dcsBind(e,this.dcsMailTo);
 this.dcsBind(e,this.dcsOffsite);
 this.dcsBind("contextmenu",this.dcsRightClick);
}
WebTrends.prototype.dcsMultiTrack=function(){
 var args=dcsMultiTrack.arguments?dcsMultiTrack.arguments:arguments;
 if (args.length%2==0){
  this.dcsSetProps(args);
  var dCurrent=new Date();
  this.DCS.dcsdat=dCurrent.getTime();
  this.dcsFPC();
  this.dcsTag();
 }
}
WebTrends.prototype.dcsCleanUp=function(){
 this.DCS={};
 this.WT={};
 this.DCSext={};
 if (arguments.length%2==0){
  this.dcsSetProps(arguments);
 }
}
WebTrends.prototype.dcsSetProps=function(args){
 for (var i=0;i<args.length;i+=2){
  if (args[i].indexOf('WT.')==0){
   this.WT[args[i].substring(3)]=args[i+1];
  }
  else if (args[i].indexOf('DCS.')==0){
   this.DCS[args[i].substring(4)]=args[i+1];
  }
  else if (args[i].indexOf('DCSext.')==0){
   this.DCSext[args[i].substring(7)]=args[i+1];
  }
 }
}
WebTrends.prototype.dcsSplit=function(list){
 var items=list.toLowerCase().split(",");
 var len=items.length;
 for (var i=0;i<len;i++){
  items[i]=items[i].replace(/^\s*/,"").replace(/\s*$/,"");
 }
 return items;
}
// Code section for Track clicks to download links.
WebTrends.prototype.dcsDownload=function(evt){
 evt=evt||(window.event||"");
 if (evt&&((typeof(evt.which)!="number")||(evt.which==1))){
  var e=this.dcsEvt(evt,"A");
  if (e.href){
   var hn=e.hostname?(e.hostname.split(":")[0]):"";
   if (this.dcsIsOnsite(hn)&&this.dcsTypeMatch(e.pathname,this.downloadtypes)){
    var qry=e.search?e.search.substring(e.search.indexOf("?")+1,e.search.length):"";
    var pth=e.pathname?((e.pathname.indexOf("/")!=0)?"/"+e.pathname:e.pathname):"/";
    var ttl="";
    var text=document.all?e.innerText:e.text;
    var img=this.dcsEvt(evt,"IMG");
    if (img.alt){
     ttl=img.alt;
    }
    else if (text){
     ttl=text;
    }
    else if (e.innerHTML){
     ttl=e.innerHTML;
    }
    this.dcsMultiTrack("DCS.dcssip",hn,"DCS.dcsuri",pth,"DCS.dcsqry",e.search||"","WT.ti","Download:"+ttl,"WT.dl","20","WT.nv",this.dcsNavigation(evt));
    this.DCS.dcssip=this.DCS.dcsuri=this.DCS.dcsqry=this.WT.ti=this.WT.dl=this.WT.nv="";
   }
  }
 }
}
// Code section for Track right clicks to download links.
WebTrends.prototype.dcsRightClick=function(evt){
 evt=evt||(window.event||"");
 if (evt){
  var btn=evt.which||evt.button;
  if ((btn!=1)||(navigator.userAgent.indexOf("Safari")!=-1)){
   var e=this.dcsEvt(evt,"A");
   if ((typeof(e.href)!="undefined")&&e.href){
    if ((typeof(e.protocol)!="undefined")&&e.protocol&&(e.protocol.indexOf("http")!=-1)){
     if ((typeof(e.pathname)!="undefined")&&this.dcsTypeMatch(e.pathname,this.downloadtypes)){
      var pth=e.pathname?((e.pathname.indexOf("/")!=0)?"/"+e.pathname:e.pathname):"/";
      var hn=e.hostname?(e.hostname.split(":")[0]):"";
      this.dcsMultiTrack("DCS.dcssip",hn,"DCS.dcsuri",pth,"DCS.dcsqry","","WT.ti","RightClick:"+pth,"WT.dl","25");
      this.DCS.dcssip=this.DCS.dcsuri=this.WT.ti=this.WT.dl=this.WT.nv="";
     }
    }
   }
  }
 }
}
// Code section for Track clicks to MailTo links.
WebTrends.prototype.dcsMailTo=function(evt){
 evt=evt||(window.event||"");
 if (evt&&((typeof(evt.which)!="number")||(evt.which==1))){
  var e=this.dcsEvt(evt,"A");
  if (e.href&&e.protocol){
   var qry=e.search?e.search.substring(e.search.indexOf("?")+1,e.search.length):"";
   if (e.protocol.toLowerCase()=="mailto:"){
    this.dcsMultiTrack("DCS.dcssip","","DCS.dcsuri",e.href,"WT.ti","MailTo:"+e.innerHTML,"WT.dl","23","WT.nv",this.dcsNavigation(evt));
    this.DCS.dcssip=this.DCS.dcsuri=this.WT.ti=this.WT.dl=this.WT.nv="";
   }
  }
 }
}
// Code section for Track clicks to links leading offsite.
WebTrends.prototype.dcsOffsite=function(evt){
 evt=evt||(window.event||"");
 if (evt&&((typeof(evt.which)!="number")||(evt.which==1))){
  var e=this.dcsEvt(evt,"A");
  if (e.href){
   var hn=e.hostname?(e.hostname.split(":")[0]):"";
   var pr=e.protocol||"";
   if ((hn.length>0)&&(pr.indexOf("http")==0)&&!this.dcsIsOnsite(hn)){
    var qry=e.search?e.search.substring(e.search.indexOf("?")+1,e.search.length):"";
    var pth=e.pathname?((e.pathname.indexOf("/")!=0)?"/"+e.pathname:e.pathname):"/";
    this.dcsMultiTrack("DCS.dcssip",hn,"DCS.dcsuri",pth,"DCS.dcsqry",this.trimoffsiteparams?"":qry,"DCS.dcsref",window.location,"WT.ti","Offsite:"+hn+pth+"?"+qry,"WT.dl","24","WT.nv",this.dcsNavigation(evt));
    this.DCS.dcssip=this.DCS.dcsuri=this.DCS.dcsqry=this.DCS.dcsref=this.WT.ti=this.WT.dl=this.WT.nv="";
   }
  }
 }
}

WebTrends.prototype.dcsAdv=function(){
 if (this.trackevents&&(typeof(this.dcsET)=="function")){
  this.dcsET();
 }
 this.dcsFPC();
 this.dcsAdSearch();
}
WebTrends.prototype.dcsVar=function(){
 var dCurrent=new Date();
 var WT=this.WT;
 var DCS=this.DCS;
 WT.tz=parseInt(dCurrent.getTimezoneOffset()/60*-1)||"0";
 WT.bh=dCurrent.getHours()||"0";
 WT.ul=navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
 if (typeof(screen)=="object"){
  WT.cd=navigator.appName=="Netscape"?screen.pixelDepth:screen.colorDepth;
  WT.sr=screen.width+"x"+screen.height;
 }
 if (typeof(navigator.javaEnabled())=="boolean"){
  WT.jo=navigator.javaEnabled()?"Yes":"No";
 }
 if (document.title){
  if (window.RegExp){
   var tire=new RegExp("^"+window.location.protocol+"//"+window.location.hostname+"\\s-\\s");
   WT.ti=document.title.replace(tire,"");
  }
  else{
   WT.ti=document.title;
  }
 }
 WT.js="Yes";
 WT.jv=(function(){
  var agt=navigator.userAgent.toLowerCase();
  var major=parseInt(navigator.appVersion);
  var mac=(agt.indexOf("mac")!=-1);
  var ff=(agt.indexOf("firefox")!=-1);
  var ff0=(agt.indexOf("firefox/0.")!=-1);
  var ff10=(agt.indexOf("firefox/1.0")!=-1);
  var ff15=(agt.indexOf("firefox/1.5")!=-1);
  var ff20=(agt.indexOf("firefox/2.0")!=-1);
  var ff3up=(ff&&!ff0&&!ff10&!ff15&!ff20);
  var nn=(!ff&&(agt.indexOf("mozilla")!=-1)&&(agt.indexOf("compatible")==-1));
  var nn4=(nn&&(major==4));
  var nn6up=(nn&&(major>=5));
  var ie=((agt.indexOf("msie")!=-1)&&(agt.indexOf("opera")==-1));
  var ie4=(ie&&(major==4)&&(agt.indexOf("msie 4")!=-1));
  var ie5up=(ie&&!ie4);
  var op=(agt.indexOf("opera")!=-1);
  var op5=(agt.indexOf("opera 5")!=-1||agt.indexOf("opera/5")!=-1);
  var op6=(agt.indexOf("opera 6")!=-1||agt.indexOf("opera/6")!=-1);
  var op7up=(op&&!op5&&!op6);
  var jv="1.1";
  if (ff3up){
   jv="1.8";
  }
  else if (ff20){
   jv="1.7";
  }
  else if (ff15){
   jv="1.6";
  }
  else if (ff0||ff10||nn6up||op7up){
   jv="1.5";
  }
  else if ((mac&&ie5up)||op6){
   jv="1.4";
  }
  else if (ie5up||nn4||op5){
   jv="1.3";
  }
  else if (ie4){
   jv="1.2";
  }
  return jv;
 })();
 WT.ct="unknown";
 if (document.body&&document.body.addBehavior){
  try{
   document.body.addBehavior("#default#clientCaps");
   WT.ct=document.body.connectionType||"unknown";
   document.body.addBehavior("#default#homePage");
   WT.hp=document.body.isHomePage(location.href)?"1":"0";
  }
  catch(e){
  }
 }
 if (document.all){
  WT.bs=document.body?document.body.offsetWidth+"x"+document.body.offsetHeight:"unknown";
 }
 else{
  WT.bs=window.innerWidth+"x"+window.innerHeight;
 }
 WT.fv=(function(){
  var i,flash;
  if (window.ActiveXObject){
   for(i=10;i>0;i--){
    try{
     flash=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
     return i+".0";
    }
    catch(e){
    }
   }
  }
  else if (navigator.plugins&&navigator.plugins.length){
   for (i=0;i<navigator.plugins.length;i++){
    if (navigator.plugins[i].name.indexOf('Shockwave Flash')!=-1){
     return navigator.plugins[i].description.split(" ")[2];
    }
   }
  }
  return "Not enabled";
 })();
 WT.slv=(function(){
  var slv="Not enabled";
  try{     
   if (navigator.userAgent.indexOf('MSIE')!=-1){
    var sli = new ActiveXObject('AgControl.AgControl');
    if (sli){
     slv="Unknown";
    }
   }
   else if (navigator.plugins["Silverlight Plug-In"]){
    slv="Unknown";
   }
  }
  catch(e){
  }
  if (slv!="Not enabled"){
   var i,j,v;
   if ((typeof(Silverlight)=="object")&&(typeof(Silverlight.isInstalled)=="function")){
    for(i=3;i>0;i--){
     for (j=9;j>=0;j--){
      v=i+"."+j;
      if (Silverlight.isInstalled(v)){
       slv=v;
       break;
      }
     }
     if (slv==v){
      break;
     }
    }
   }
  }
  return slv;
 })();
 if (this.i18n){
  if (typeof(document.defaultCharset)=="string"){
   WT.le=document.defaultCharset;
  } 
  else if (typeof(document.characterSet)=="string"){
   WT.le=document.characterSet;
  }
  else{
   WT.le="unknown";
  }
 }
 WT.tv="8.6.2";
 // WT.sp="@@SPLITVALUE@@";
 WT.dl="0";
 WT.ssl=(window.location.protocol.indexOf('https:')==0)?"1":"0";
 DCS.dcsdat=dCurrent.getTime();
 DCS.dcssip=window.location.hostname;
 DCS.dcsuri=window.location.pathname;
 WT.es=DCS.dcssip+DCS.dcsuri;
 if (window.location.search){
  DCS.dcsqry=window.location.search;
 }
 if (DCS.dcsqry){
  var dcsqry=DCS.dcsqry.toLowerCase();
  var params=this.paidsearchparams.length?this.paidsearchparams.toLowerCase().split(","):[];
  for (var i=0;i<params.length;i++){
   if (dcsqry.indexOf(params[i]+"=")!=-1){
    WT.srch="1";
    break;
   }
  }
 }
 if ((window.document.referrer!="")&&(window.document.referrer!="-")){
  if (!(navigator.appName=="Microsoft Internet Explorer"&&parseInt(navigator.appVersion)<4)){
   DCS.dcsref=window.document.referrer;
  }
 }
}
WebTrends.prototype.dcsEscape=function(S, REL){
 if (REL!=""){
  S=S.toString();
  for (var R in REL){
   if (REL[R] instanceof RegExp){
    S=S.replace(REL[R],R);
   }
  }
  return S;
 }
 else{
  return escape(S);
 }
}
WebTrends.prototype.dcsA=function(N,V){
 if (this.i18n&&(this.exre!="")&&!this.exre.test(N)){
  if (N=="dcsqry"){
   var newV="";
   var params=V.substring(1).split("&");
   for (var i=0;i<params.length;i++){
    var pair=params[i];
    var pos=pair.indexOf("=");
    if (pos!=-1){
     var key=pair.substring(0,pos);
     var val=pair.substring(pos+1);
     if (i!=0){
      newV+="&";
     }
     newV+=key+"="+this.dcsEncode(val);
    }
   }
   V=V.substring(0,1)+newV;
  }
  else{
   V=this.dcsEncode(V);
  }
 }
 return "&"+N+"="+this.dcsEscape(V, this.re);
}
WebTrends.prototype.dcsEncode=function(S){
 return (typeof(encodeURIComponent)=="function")?encodeURIComponent(S):escape(S);
}
WebTrends.prototype.dcsCreateImage=function(dcsSrc){
 this.images[this.index]=new Image();
 this.images[this.index].src=dcsSrc;
 this.index++;
}
WebTrends.prototype.dcsMeta=function(){
 var elems;
 if (document.all){
  elems=document.all.tags("meta");
 }
 else if (document.documentElement){
  elems=document.getElementsByTagName("meta");
 }
 if (typeof(elems)!="undefined"){
  var length=elems.length;
  for (var i=0;i<length;i++){
   var name=elems.item(i).name;
   var content=elems.item(i).content;
   var equiv=elems.item(i).httpEquiv;
   if (name.length>0){
    if (name.toUpperCase().indexOf("WT.")==0){
     this.WT[name.substring(3)]=content;
    }
    else if (name.toUpperCase().indexOf("DCSEXT.")==0){
     this.DCSext[name.substring(7)]=content;
    }
    else if (name.toUpperCase().indexOf("DCS.")==0){
     this.DCS[name.substring(4)]=content;
    }
   }
  }
 }
}
WebTrends.prototype.dcsTag=function(){
 if (document.cookie.indexOf("WTLOPTOUT=")!=-1){
  return;
 }
 var WT=this.WT;
 var DCS=this.DCS;
 var DCSext=this.DCSext;
 var i18n=this.i18n;
 var P="http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+this.domain+(this.dcsid==""?'':'/'+this.dcsid)+"/dcs.gif?";
 if (i18n){
  WT.dep="";
 }
 for (var N in DCS){
  if (DCS[N]&&(typeof DCS[N]!="function")){
   P+=this.dcsA(N,DCS[N]);
  }
 }
 var keys=["co_f","vtid","vtvs","vt_f_tlv"];
 for (var i=0;i<keys.length;i++){
  var key=keys[i];
  if (WT[key]){
   P+=this.dcsA("WT."+key,WT[key]);
   delete WT[key];
  }
 }
 for (N in WT){
  if (WT[N]&&(typeof WT[N]!="function")){
   P+=this.dcsA("WT."+N,WT[N]);
  }
 }
 for (N in DCSext){
  if (DCSext[N]&&(typeof DCSext[N]!="function")){
   if (i18n){
    WT.dep=(WT.dep.length==0)?N:(WT.dep+";"+N);
   }
   P+=this.dcsA(N,DCSext[N]);
  }
 }
 if (i18n&&(WT.dep.length>0)){
  P+=this.dcsA("WT.dep",WT.dep);
 }
 if (P.length>2048&&navigator.userAgent.indexOf('MSIE')>=0){
  P=P.substring(0,2040)+"&WT.tu=1";
 }
 this.dcsCreateImage(P);
 this.WT.ad="";
}
WebTrends.prototype.dcsCollect=function(){
 if (this.enabled){
  this.dcsVar();
  this.dcsMeta();
  this.dcsAdv();
  this.dcsTag();
 }
}

function dcsMultiTrack(){
 if (typeof(_tag)!="undefined"){
  return(_tag.dcsMultiTrack());
 }
}

$(window).load(function onWindowLoadWebtrends(){
setTimeout(function(){
  webTrendsInstance = new WebTrends(dataFromNotes.trackingId);
    webTrendsInstance.dcsGetId(function(){
     webTrendsInstance.dcsCollect(); 
  });
},10);
});

Novasol.Webtrends = {
 setDataFromNotes: function(data) {
  dataFromNotes = data;
 }  
};
 
})(jQuery);
/** webtrends.init.js **/

Novasol.Webtrends.setDataFromNotes({
 trackingId: 'dcswk9370dm1b3ome0gwktf2a_3z2e' 
});


/** Lazyload_trigger.js must be last **/
Novasol.Lazyload.load();

