
(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 getCachedTemplates(){return{'createNewMyFavouritesList':'<form class=\"favorites-overlay sendMyFavouritesConfirmation use-default-validation\" action=\"#\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteCreateListHeader?><\/div>\t<? if (viewData.showError) { ?><p><?=Novasol.Systext.MyFavouriteMailAlreadyUsed?><\/p><? } ?>\t<? if (viewData.showHint) { ?><p><?=Novasol.Systext.MyFavouriteCreateHint?><\/p><? } ?>\t<p><?=Novasol.Systext.MyFavouriteCreateFillInHint?><\/p>\t<p class=\"mandatory-notice low-prio-copy\"><?=Novasol.Systext.ValidationHint?><\/p>\t<fieldset>\t\t<label for=\"email\"><?=Novasol.Systext.MyFavouriteMailLabel?> *<\/label>\t\t<input id=\"email\" class=\"mandatory validate-email\" type=\"text\" value=\"<?=viewData.email ? viewData.email : \'\'?>\" \/>\t<\/fieldset>\t<fieldset>\t\t<label for=\"password\"><?=Novasol.Systext.MyFavouritePasswordLabel?> *<\/label>\t\t<input id=\"password\" class=\"mandatory\" type=\"password\" value=\"<?=viewData.password ? viewData.password : \'\'?>\" \/>\t<\/fieldset>\t<fieldset class=\"buttons\">\t\t<button class=\"blue\" type=\"submit\"><span>\t\t\t\t<? if (viewData.showHint) { ?>\t\t\t\t<?=Novasol.Systext.CreateButtonWithHint?>\t\t\t\t<? } else { ?>\t\t\t\t<?=Novasol.Systext.CreateButton?>\t\t\t\t<? } ?>\t\t\t<\/span><\/button>\t\t<button class=\"blue hide-overlay\"><span>\t\t\t\t<? if (viewData.showHint) { ?>\t\t\t\t<?=Novasol.Systext.CancelButtonWithHint?>\t\t\t\t<? } else { ?>\t\t\t\t<?=Novasol.Systext.CancelButton?>\t\t\t\t<? } ?>\t\t\t<\/span><\/button>\t<\/fieldset><\/form>','quicksearch-duration-dropdown-template':'<option value=\"\"><?=Novasol.Systext.SEARCH_FILTER_DURATIONLABEL?><\/option><optgroup label=\"<?=Novasol.Systext.SEARCH_FILTER_MOSTCOMMON?>\">\t<option value=\"7\" data-label=\"1w\">1 <?=Novasol.Systext.SEARCH_FILTER_WEEK?><\/option>\t<option value=\"14\" data-label=\"2w\">2 <?=Novasol.Systext.SEARCH_FILTER_WEEKS?><\/option>\t<option value=\"21\" data-label=\"3w\">3 <?=Novasol.Systext.SEARCH_FILTER_WEEKS?><\/option><\/optgroup><optgroup label=\"<?=Novasol.Systext.SEARCH_FILTER_SHORTSTAYS?>\">\t<? for(var i = viewData.minNights,len=7;i<len;i++) { ?>\t<option value=\"<?=i?>\"><?=i?> <? if(i==1){ ?><?=Novasol.Systext.SEARCH_FILTER_NIGHT?><? } else { ?><?=Novasol.Systext.SEARCH_FILTER_NIGHTS?><? } ?><\/option>\t<? } ?>\t<option value=\"7\">7 <?=Novasol.Systext.SEARCH_FILTER_NIGHTS?> (1 <?=Novasol.Systext.SEARCH_FILTER_WEEK?>)<\/option><\/optgroup><optgroup name=\"olos\" label=\"<?=Novasol.Systext.SEARCH_FILTER_OTHERSTAYS?>\">\t<? if(viewData.duration && viewData.duration > 7 && viewData.duration != 14 && viewData.duration != 21) { ?>\t<option value=\"<?=viewData.duration?>\" id=\"custom-duration\"><? \t\tif(viewData.duration%7){ \t\t?><?=viewData.duration?> <?=Novasol.Systext.SEARCH_FILTER_NIGHTS?><? } \t\telse { \t\t?><?=viewData.duration\/7?> <?=Novasol.Systext.SEARCH_FILTER_WEEKS?><? \t\t} ?><\/option>\t<?}?>\t<option name=\"altDur\" value=\"\"><?=Novasol.Systext.SEARCH_FILTER_DURATION?><\/option><\/optgroup>','quicksearch-duration-template':'<div id=\"quicksearch-duration\">\t<div class=\"l-header\"><?=Novasol.Systext.quicksearch_duration_overlay_headline?><\/div>\t<div class=\"col\">\t\t<? \t\tvar max=84, nightPlur = \' \'+Novasol.Systext.SEARCH_FILTER_NIGHTS, nightSing = \' \'+Novasol.Systext.SEARCH_FILTER_NIGHT,weekPlur=Novasol.Systext.search_filter_weeks,weekSing=Novasol.Systext.search_filter_weeks;\t\tfor(var i=1,week;i<=max;i++) {?>\t\t<? if(i%7) {?>\t\t<a data-value=\"<?=i?>\"><?=i?> <?=i>1?nightPlur:nightSing?><\/a>\t\t<? } else { week = i\/7;?>\t\t<a data-value=\"<?=i?>\"><?=week?> <?=week>1?weekPlur:weekSing?><\/a>\t\t<? } if(i%14==0 && i != max) {?>\t<\/div>\t<div class=\"col\">\t\t<? } else if(i%7==0) {?>\t\t<br\/>\t\t<?}}?>\t<\/div><\/div>','availability_message_template':'<? for(var i=0,message;message=viewData.messages[i];i++){ ?><div class=\"availabilityMessage house-error\"><?=message?><\/div><? } ?>','openMyBooking':'<form class=\"favorites-overlay openMyBooking use-default-validation\" action=\"#\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteOpenMyBookingHeader?><\/div>\t<p><?=Novasol.Systext.MyFavouriteOpenMyBookingHint?><\/p>\t<p class=\"mandatory-notice low-prio-copy\"><?=Novasol.Systext.ValidationHint?><\/p>\t<fieldset>\t\t<label for=\"bookingNumber\"><?=Novasol.Systext.MyFavouriteBookingNumberLabel?> *<\/label>\t\t<input id=\"bookingNumber\" class=\"mandatory\" type=\"text\" value=\"\" \/>\t<\/fieldset>\t<fieldset>\t\t<label for=\"productNumber\"><?=Novasol.Systext.MyFavouriteProductNumberLabel?> *<\/label>\t\t<input id=\"productNumber\" class=\"mandatory\" type=\"text\" value=\"\" \/>\t<\/fieldset>\t<fieldset>\t\t<label for=\"email\"><?=Novasol.Systext.MyFavouriteMailLabel?> *<\/label>\t\t<input id=\"email\" class=\"mandatory validate-email\" type=\"text\" value=\"\" \/>\t<\/fieldset>\t<fieldset class=\"buttons\">\t\t<button class=\"blue\" type=\"submit\"><span><?=Novasol.Systext.OpenButton?><\/span><\/button>\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.CancelButton?><\/span><\/button>\t<\/fieldset><\/form>','myFavouritesSuperMenuTemplate':'<div id=\"myFavourites\">\t<div class=\"favourites\">\t\t<div class=\"s-header\">\t\t\t<?=Novasol.Systext.MyFavouritesLabel?> <img src=\"\/site\/redesign\/img\/favoritesIcon.png\" alt=\"\" \/> <span class=\"favoritesCounter\">(<?=viewData.counter?>)<\/span>\t\t<\/div>\t\t<div class=\"houselist\">\t\t\t<? var favourites = viewData.favourites; for (var i = 0, length = Math.min(6, favourites.length); i < length; i++) { var favourite = favourites[i]; ?>\t\t\t<a href=\"<?=favourite.housePresentationURL?>\"><img alt=\"<?=favourite.id?>\" src=\"<?=favourite.imageURL?>\"><\/a>\t\t\t<? } ?>\t\t\t<? if (favourites.length < 6) { for (var j = 0, secondLength = 6 - favourites.length; j < secondLength; j++) { ?>\t\t\t<a class=\"placeHolder\"><img src=\"\/site\/redesign\/img\/productPlaceholder.png\" \/><\/a>\t\t\t<? }} ?>\t\t<\/div>\t\t<? if (viewData.favourites && viewData.favourites.length > 0) { ?>\t\t<div class=\"options hasList\">\t\t\t<span class=\"key\">\t\t\t\t<?=Novasol.Systext.MyFavouritesViewAsLabel?>\t\t\t<\/span>\t\t\t<div class=\"functionalityContainer\">\t\t\t\t<a class=\"functionality\" data-action=\"list\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"viewList\" \/><?=Novasol.Systext.MyFavouritesViewAsList?><\/a>\t\t\t\t<a class=\"functionality\" data-action=\"gallery\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"viewGallery\" \/><?=Novasol.Systext.MyFavouritesViewAsGallery?><\/a>\t\t\t\t<a class=\"functionality\" data-action=\"map\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"viewMap\" \/><?=Novasol.Systext.MyFavouritesViewAsMap?><\/a>\t\t\t<\/div>\t\t<\/div>\t\t<? } ?>\t\t<div class=\"options\" style=\"overflow: hidden; clear: left\">\t\t\t<span class=\"key\">\t\t\t\t<?=Novasol.Systext.MyFavouritesListActionLabel?>:\t\t\t<\/span>\t\t\t<div class=\"functionalityContainer\">\t\t\t\t<? if (!viewData.isLoggedIn) { ?><a class=\"functionality\" data-action=\"open\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"open\" \/><?=Novasol.Systext.MyFavouritesListOpen?><\/a><? } ?>\t\t\t\t<? if (!viewData.isLoggedIn && viewData.favourites && viewData.favourites.length > 0) { ?><a class=\"hasList functionality\" data-action=\"save\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"save\" \/><?=Novasol.Systext.MyFavouritesListSave?><\/a><? } ?>\t\t\t\t<? if (viewData.favourites && viewData.favourites.length > 0) { ?><a class=\"hasList functionality\" data-action=\"clear\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"clear\" \/><?=Novasol.Systext.MyFavouritesListClear?><\/a><? } ?>\t\t\t\t<? if (viewData.favourites && viewData.favourites.length > 0) { ?><a class=\"hasList functionality\" data-action=\"send\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"send\" \/><?=Novasol.Systext.MyFavouritesListSend?><\/a><? } ?>\t\t\t\t<? if (viewData.isLoggedIn) { ?><a class=\"hasList functionality\" data-action=\"logout\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"logout\" \/><?=Novasol.Systext.MyFavouritesListLogout?><\/a><? } ?>\t\t\t<\/div>\t\t<\/div>\t<\/div>\t<div class=\"recentlyViewed\">\t\t<div class=\"s-header\">\t\t\t<?=Novasol.Systext.MyFavouritesViewAs?>\t\t<\/div>\t\t<? var recentlyViewedProducts = viewData.recentlyViewedProducts; if (recentlyViewedProducts.length) { ?>\t\t<div class=\"houselist\">\t\t\t<? for (var i = 0, length = Math.min(6, recentlyViewedProducts.length); i < length; i++) { var recentlyViewedProduct = recentlyViewedProducts[i]; ?>\t\t\t<a href=\"<?=recentlyViewedProduct.housePresentationURL?>\"><img alt=\"<?=recentlyViewedProduct.id?>\" src=\"<?=recentlyViewedProduct.imageURL?>\"><\/a>\t\t\t<? } ?>\t\t\t<? if (recentlyViewedProducts.length < 6) { for (var j = 0, secondLength = 6 - recentlyViewedProducts.length; j < secondLength; j++) { ?>\t\t\t<a class=\"placeHolder\"><img src=\"\/site\/redesign\/img\/productPlaceholder.png\" \/><\/a>\t\t\t<? }} ?>\t\t<\/div>\t\t<? } else { ?>\t\t<div class=\"options\">\t\t\t<a class=\"functionality\" data-action=\"openDefaultSearchResultPage\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"openDefaultSearchResultPage\" \/><?=Novasol.Systext.MyFavouriteEmptyRecentlyViewedHint?><\/a>\t\t<\/div>\t\t<? } ?>\t<\/div>\t<div class=\"my-booking\">\t\t<div class=\"s-header\">\t\t\t<?=Novasol.Systext.MyFavouritesMyBookingLabel?>\t\t<\/div>\t\t<div class=\"options\">\t\t\t<a class=\"functionality\" data-action=\"openMyBooking\"><img src=\"\/site\/redesign\/img\/spacer.gif\" class=\"openMyBooking\" \/><?=Novasol.Systext.MyFavouritesOpenMyBooking?><\/a>\t\t<\/div>\t<\/div><\/div>','sendMyFavouritesConfirmation':'<div class=\"favorites-overlay sendMyFavouritesConfirmation\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteSendListConfirmationHeader?><\/div>\t<? if (viewData.mailSent) { ?>\t<p><?=Novasol.Systext.MyFavouriteSendListConfirmationTemplate.replace(\"$mailToken\", viewData.email)?><\/p>\t<? } else {?>\t<p><?=Novasol.Systext.MyFavouriteListNotSentMessage?><\/p>\t<? } ?>\t<fieldset class=\"buttons\">\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.OkButton?><\/span><\/button>\t<\/fieldset><\/div>','openPreviouslySavedMyFavouritesList':'<form class=\"favorites-overlay openPreviouslySavedMyFavouritesList use-default-validation\" action=\"#\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteOpenListHeader?><\/div>\t<? if (viewData.showError) { ?><p><strong><?=Novasol.Systext.MyFavouriteOpenListNotFound?><\/strong><\/p><? } ?>\t<p><?=Novasol.Systext.MyFavouriteOpenFillInHint?><\/p>\t<p class=\"mandatory-notice low-prio-copy\"><?=Novasol.Systext.ValidationHint?><\/p>\t<fieldset>\t\t<label for=\"email\"><?=Novasol.Systext.MyFavouriteMailLabel?> *<\/label>\t\t<input id=\"email\" class=\"mandatory validate-email\" type=\"text\" value=\"<?=viewData.email ? viewData.email : \'\'?>\" \/>\t<\/fieldset>\t<fieldset>\t\t<label for=\"password\"><?=Novasol.Systext.MyFavouritePasswordLabel?> *<\/label>\t\t<input id=\"password\" class=\"mandatory\" type=\"password\" value=\"<?=viewData.password ? viewData.password : \'\'?>\" \/>\t<\/fieldset>\t<fieldset>\t\t<label class=\"with-checkbox\"><input type=\"checkbox\" name=\"ADD\" \/> <?=Novasol.Systext.MyFavouriteAddExistingHouses?><\/label>\t<\/fieldset>\t<fieldset class=\"buttons\">\t\t<button class=\"blue\" type=\"submit\"><span><?=Novasol.Systext.OpenButton?><\/span><\/button>\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.CancelButton?><\/span><\/button>\t<\/fieldset>\t<fieldset class=\"buttons\">\t\t<a class=\"favClickable\" data-action=\"forgot\"><?=Novasol.Systext.MyFavouriteForgotMyPasswordLink?><\/a>\t<\/fieldset>  <\/form>','createNewMyFavouritesListConfirmation':'<div class=\"favorites-overlay createNewMyFavouritesListConfirmation\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteCreateNewListConfirmationHeader?><\/div>\t<? if (viewData.listCreated) { ?><p><?=Novasol.Systext.MyFavouriteCreateNewListConfirmation?><\/p><? } else { ?>\t<p><?=Novasol.Systext.MyFavouriteCreateNewListFailure?><\/p>\t<? } ?>\t<fieldset class=\"buttons\">\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.OkButton?><\/span><\/button>\t<\/fieldset><\/div>','clearMyFavourites':'<form class=\"favorites-overlay clearMyFavourites use-default-validation\" action=\"#\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouritesClearHeader?><\/div>\t<p><?=Novasol.Systext.MyFavouritesClearWarning?><\/p>\t<fieldset class=\"buttons\">\t\t<button class=\"blue\" type=\"submit\"><span><?=Novasol.Systext.MyFavouritesYes?><\/span><\/button>\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.MyFavouritesNo?><\/span><\/button>\t<\/fieldset><\/form>','quicksearch-numberofpersons-template':'<div class=\"inputcontainer\">\t<select name=\"adults\" class=\"adults\">\t\t<option value=\"1\">1 <?=Novasol.Systext.SEARCH_FILTER_ADULT?><\/option>\t\t<? for(var i=2;i<=30;i++) { ?>\t\t<option value=\"<?=i?>\"><?=i?> <?=Novasol.Systext.SEARCH_FILTER_ADULTS?><\/option>\t\t<? } ?>\t<\/select>\t<select name=\"children\" class=\"children\">\t\t<option value=\"0\">0 <?=Novasol.Systext.SEARCH_FILTER_CHILDREN?><\/option>\t\t<option value=\"1\">1 <?=Novasol.Systext.SEARCH_FILTER_CHILD?><\/option>\t\t<? for(var i=2;i<=30;i++) { ?>\t\t<option value=\"<?=i?>\"><?=i?> <?=Novasol.Systext.SEARCH_FILTER_CHILDREN?><\/option>\t\t<? } ?>\t<\/select>\t<select name=\"infants\" class=\"infants\" style=\"display:none\">\t\t<option value=\"0\">0 <?=Novasol.Systext.SEARCH_FILTER_INFANTS?><\/option>\t\t<option value=\"1\">1 <?=Novasol.Systext.SEARCH_FILTER_INFANT?><\/option>\t\t<? for(var i=2;i<=30;i++) { ?>\t\t<option value=\"<?=i?>\"><?=i?> <?=Novasol.Systext.SEARCH_FILTER_INFANTS?><\/option>\t\t<? } ?>\t<\/select><\/div><button class=\"blue\" type=\"submit\"><span><?=Novasol.Systext.OkButton?><\/span><\/button>','forgotMyPasswordConfirmation':'<div class=\"favorites-overlay forgotMyPasswordConfirmation\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteForgotMyPasswordConfirmationHeader?><\/div>\t<? if (viewData.mailSent) { ?><p><?=Novasol.Systext.forgotMyPasswordConfirmation?><\/p><? } else { ?>\t<p><?=Novasol.Systext.forgotMyPasswordConfirmation?><\/p>\t<? } ?>\t<fieldset class=\"buttons\">\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.OkButton?><\/span><\/button>\t<\/fieldset><\/div>','forgotMyPassword':'<form class=\"favorites-overlay forgotMyPassword use-default-validation\" action=\"#\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouriteForgotMyPasswordHeader?><\/div>\t<p class=\"mandatory-notice low-prio-copy\"><?=Novasol.Systext.ValidationHint?><\/p>\t<fieldset>\t\t<label for=\"email\"><?=Novasol.Systext.MyFavouriteMailLabel?> *<\/label>\t\t<input id=\"email\" class=\"mandatory validate-email\" type=\"text\" value=\"\" \/>\t<\/fieldset>\t<fieldset class=\"buttons\">\t\t<button class=\"blue\" type=\"submit\"><span><?=Novasol.Systext.SubmitButton?><\/span><\/button>\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.CancelButton?><\/span><\/button>\t<\/fieldset><\/form>','sendMyFavourites':'<form class=\"favorites-overlay sendMyFavourites use-default-validation\" action=\"#\">\t<div class=\"s-header\"><?=Novasol.Systext.MyFavouritesSendListHeader?><\/div>\t<p class=\"mandatory-notice low-prio-copy\"><?=Novasol.Systext.ValidationHint?><\/p>\t<fieldset>\t\t<? if (viewData.isLoggedIn) { ?>\t\t<label for=\"mailType1\" class=\"with-checkbox\">\t\t\t<? } else { ?>\t\t\t<label for=\"mailType1\" style=\"display:none\">\t\t\t\t<? } ?>\t\t\t\t<input type=\"radio\" name=\"mailType\" value=\"asList\" checked id=\"mailType1\" \/> <?=Novasol.Systext.MyFavouriteSendAsList?>\t\t\t<\/label>\t\t\t<? if (viewData.isLoggedIn) { ?>\t\t\t<label for=\"mailType2\" class=\"with-checkbox\">\t\t\t\t<? } else { ?>\t\t\t\t<label for=\"mailType2\" style=\"display:none\">\t\t\t\t\t<? } ?>\t\t\t\t\t<input type=\"radio\" name=\"mailType\" value=\"asRef\" id=\"mailType2\"\/> <?=Novasol.Systext.MyFavouriteSendAsRef?>\t\t\t\t<\/label>\t\t\t\t<\/fieldset>\t\t\t\t<fieldset>\t\t\t\t\t<label for=\"email\"><?=Novasol.Systext.MyFavouriteSendListEmailLabel?> *<\/label>\t\t\t\t\t<input id=\"email\" class=\"validate-email mandatory\" type=\"text\" value=\"\" \/>\t\t\t\t<\/fieldset>\t\t\t\t<fieldset class=\"buttons\">\t\t\t\t\t<button class=\"blue\" type=\"submit\"><span><?=Novasol.Systext.SendButton?><\/span><\/button>\t\t\t\t\t<button class=\"blue hide-overlay\"><span><?=Novasol.Systext.CancelButton?><\/span><\/button>\t\t\t\t<\/fieldset>\t\t\t\t<\/form>'};}/** templates.js **/

(function templatesClosure($, undefined) {
	var templates = typeof getCachedTemplates === 'function'?getCachedTemplates():{};

	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] = templates[id]
					.replace(/[\r\t\n]/g, " ")
					.replace(/<\?/g, "\t");
					while(templates[id].search(/((^|\?>)[^\t]*)'/)!==-1) {
						templates[id] = templates[id].replace(/((^|\?>)[^\t]*)'/g, "$1\r");
					}
					templates[id] = templates[id].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); } }";
			fnCode += templates[id];
			try {
				templates[id] = new Function("viewData", fnCode);
			}
			catch(e) {
				throw ('[Templates] ' + id + ' contains invalid code:\n'+fnCode);
			}
		}
		return templates[id](data);
	};



Novasol.Templates = {
		parse: parse
	};

})(jQuery);
(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;
	},
	fixEDfieldBasedOnSDandDUR: function() {
		var $ED = this.find('[name=ED]'),
		sdVal = this.find('[name=SD]').val(),
		duration = this.find('[name=DUR]').val();

		if (!sdVal || sdVal === "" || !duration || duration === "") {
			if (!sdVal && $ED.length) {
				$ED.val("");
			}

			return this;
		}

		var sdArgs = sdVal.split('-'),
		endDate = new Date(1*sdArgs[2],1*sdArgs[1]-1,1*sdArgs[0]),
		edStr, date, month;
		endDate.setDate(endDate.getDate()+1*duration);
		date = endDate.getDate();
		month = endDate.getMonth()+1;
		edStr = (date<10?"0":"")+date+'-'+(month<10?"0":"")+month+'-'+endDate.getFullYear();
		if($ED.length) {
			$ED.val(edStr);
		}
		else {
			this.append('<input name="ED" type="hidden" value="'+edStr+'"/>');
		}
		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;
};
/**
 * How to use the valdiation framework
 *
 * Forms must have the class "use-default-validation" set and have a minimuk of two children
 * 1: a text with the class "mandatory-notice"
 * 2: a button with type="submit"
 *
 * there are 3 basic ways to set up field
 *
 * 1: "mandatory" (no blanks allowed)
 * 2: "validate-email" (blanks allowed, if non-blank, then must have valid email format)
 * 3: "validate-email mandatory" (must be valid email format)
 *
 * if "mandatory" is set on a checkbox, then the value doesn't matter, but the checkbox must be checked
 *
 * Instead of binding to form "submit" event, bind to "validation-success"/ "validation-fail" instead
 *
 * $(domFormElm).bind("validation-success",onSuccessFunction)
 *
 * the validation framework automatically call "e.preventdefault()" on all form submitions, so if you need to
 * submit a form (and not do ajax) then you hagve to call the "submiot" method omn the domForm element.
 * DO NOT: use jQuerys built in submit, it will be prevented by the framework.
 * DO:
 *
 * $(domFormElm).bind("validation-success",onSuccessFunction);
 * function onSuccessFunction() {
 *  this.submit();
 * }
 *
 * example form:
 *
 * <form class="use-default-validation">
 * <div>
 * <span class="mandatory-notice">Fields marked with * are mandatory</span>
 * </div>
 * <input class="mandatory" />
 * <input class="validate-email mandatory" />
 * <input class="validate-email" />
 * <input/>
 * <button type="submit"></button>
 * </form>
 */

(function formsValidationClosure($,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($field.is(':checkbox')) {
			return !!$field.prop('checked');
		}
		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 $form = $(this);
		if(!checkMandatoryFields(this)) {
			$form.trigger('validation-fail').placeholder();
			return false;
		}
		else {
			$form.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 utilsClosure($, undefined){

	var paramMap;

	function getParametersAsMap() {
		if(paramMap) {
			return paramMap;
		}
		paramMap = {};
		var  pairs = location.search.substring(1).split("&");
		for(var i=0,pair;pair=pairs[i]; i++) {
			if ((pair=pair.split('=')).length == 2) {
				paramMap[pair.shift()] = unescape(pair.shift());
			}
		}
		return paramMap;
	}


	function updateQueryString( url, param, value ) {
		if(url.length==0){
			return ["?",param,"=",value].join("");
		}
		var re = new RegExp( "([?|&])" + param + "=.*?(&|$)","i" );
		if ( url.match( re ) )
			return url.replace( re,'$1' + param + "=" + value + '$2' );
		else
			return [url, url.indexOf("?")==-1?'?':'&', param, "=", value].join('');
	}

	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, " "));
	}
	
	function convertAS400Date(AS400Date){
		if(!AS400Date || AS400Date=="" || AS400Date=="00000000"){
			return new Date();
		}
		var year = AS400Date.substring(0,4),
				month = new String(1*AS400Date.substring(4,6)-1),
				day = AS400Date.substring(6,8);
		return new Date(year, month, day);
	}

	Novasol.Utils = {
		updateQueryString: updateQueryString,
		getParameterByName: getParameterByName,
		getParametersAsMap: getParametersAsMap,
		convertAS400Date: convertAS400Date
	};
})(jQuery);/** newsletter.js **/
(function newsletterClosure($,undefined){

	var dataFromNotes;

	function onUnsubscribeClick(e) {
		e.preventDefault();
		if(Novasol.Forms.checkMandatoryFields('#newsletter', this)) {
			var isIframe = $('html').hasClass('is-iframe'),
					sUrl = isIframe ? dataFromNotes.iframeUnsubscribeSuccessUrl : dataFromNotes.unsubscribeSuccessUrl,
					fUrl = isIframe ? dataFromNotes.iframeUnsubscribeFailureUrl : dataFromNotes.unsubscribeFailureUrl;

			$('<form action="http://signup.globase.com/" method="post"></form>')
			.append('<input type="hidden" name="formid" value="'+dataFromNotes.formId+'"/>')
			.append('<input type="hidden" name="licenseid" value="'+dataFromNotes.licenseId+'"/>')
			.append('<input type="hidden" name="listid" value="'+dataFromNotes.listId+'"/>')
			.append('<input type="hidden" value="'+sUrl+'" name="successurl"/>')
			.append('<input type="hidden" value="'+fUrl+'" name="failureurl"/>')
			.append('<input type="hidden" value="" name="duplicateurl"/>')
			.append('<input type="hidden" value="" name="doubleoptin"/>')
			.append('<input type="hidden" value="" name="duplicateby"/>')
			.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="'+$('#gb_email').val()+'"/>')
			.appendTo(document.body).submit();
		}
	}

	function onOpenNewsletterSubscribeOverlayClick(e) {
		e.preventDefault();
		Novasol.Overlay.showIframe(455,140,dataFromNotes.newsletterOverlayUrl);
		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();})
	});

	Novasol.Newsletter = {
		setDataFromNotes: function(data) { dataFromNotes = data;}
	};

})(jQuery);

/** newsletter.js **/
/*
(function newsletterClosure($,undefined){

	var dataFromNotes;
	
	function submitNewsletter(){
		var origin = window.location.search.substring(1);
		$("#newsletter").append('<input type="hidden" name="origin" value="'+origin+'" />');
		$.post('/newsletter',$('#newsletter').serialize(),function(reply){
			if(reply=='succes'){
				$(".grid.g3").html(Novasol.Systext.nwslttrModule_ok);
			}else{
				$(".grid.g3").html(Novasol.Systext.nwslttrModule_failure);
			}
		},"text");
	}

	function onUnsubscribeClick(e) {
		e.preventDefault();
		$('#newsletter').append('<input type="hidden" name="unsubscribe" value="true" />');
		$('#newsletter').trigger('validation-success');
	}

	function onOpenNewsletterSubscribeOverlayClick(e) {
		e.preventDefault();
		var url = window.location.pathname;
		var filename = url.substring(url.lastIndexOf('/')+1);
		Novasol.Overlay.showIframe(455,140,dataFromNotes.newsletterOverlayUrl+"?"+filename);
		return false;
	}

	$(function onDomReadyNewsletter(){ //Domready
		$(document.body).delegate('.open-newsletter-subscribe-overlay','click',onOpenNewsletterSubscribeOverlayClick);
		$('#newsletter .unsubscribe').click(onUnsubscribeClick);
		$('#newsletter').bind('validation-success',submitNewsletter)
	});

	Novasol.Newsletter = {
		setDataFromNotes: function(data) { dataFromNotes = data;}
	};

})(jQuery);
*/if(Novasol.context !== "searchresults_" && Novasol.context !== "showhouse_") {

	jQuery(function rotateImages() {
		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)';
		}
	});


}/** toolbox.js **/

(function toolboxClosure($, undefined){

	var outsideClickEntity, params = Novasol.Utils.getParametersAsMap();

	function onCollapsibleToggleClick(e) {
		$(this).closest('.collapsible-container').toggleClass('collapsed');
	}

	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);
	});

	$.extend({
		bindOutsideClick: function(selector, callback) {
			outsideClickEntity = {
				selector: selector,
				callback: callback
			};
		}
	});

	/* stuff that runs at parse time */


	/*
	 * set cookies based on querystring params. this is reuse of old logic and should probably be rewritten
	 * so it isn't based around a notes generated js file that needs to be loaded.
	 */
	if(params.A) {
		$.getScript('/house.nsf/0/cookie.js?open&A='+params.A);
		if(params.F){
			$.cookie('F',params.F,{ path: '/' });
		}
	}

})(jQuery);(function headerClosure($,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').on('mouseleave','.active',onActiveMouseleave);
		$header.find('a.sales-market').on('click', onSalesMarketClick);
		$header.find('a.house-owner').on('click mouseover', onLinkClick('.house-owner'));
		$header.find('a.partner').on('click mouseover', onLinkClick('.partner'));
		$header.find('a.help').on('click mouseover', onLinkClick('.help'));
	});

})(jQuery);/** overlay **/

(function overlayClosure($,undefined){

	var $fullFade, $overlay, $contentWrapper, $transBorder, $content, curHideCallback,$closeButton;

	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();
			positionOverlay();
		}
		else {
			$transBorder.animate(transBorder,{ duration: 150});
			$contentWrapper.animate(contentWrapper,150, positionOverlay);
			$content.html(htmlContent);
		}
		
		if(typeof hideCallback==='function') {
			curHideCallback = hideCallback;
		}
		else {
			curHideCallback = null;
		}
	}
	
	function positionOverlay(){
		if($(window).height()<$contentWrapper.outerHeight()){
			$overlay.css({position:"absolute",top:"0px"});
			$contentWrapper.css({marginTop:"-10px",top:"30px"});
			$transBorder.css({marginTop:"-20px",top:"30px"});
			$(window).scrollTop(0);
		}
	}

	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).on('click', '#overlay div.content .hide-overlay', hide);
	});

})(jQuery);
/** catalogue.js **/

if(Novasol.context === "cataloguelist_301") {

	(function cataloguesClosure($,undefined){

		var dataFromNotes;

		function onAjaxSuccess(data, textStatus, jqXHR) {
			var reply = data.split("|");
			var viewModel = {
				catalogue:reply[0]=='success',
				message:reply[0]
			}
			if(reply[1]!=""){
				viewModel.newsletter = reply[1];
			}
			if(viewModel.catalogue) {
				Novasol.Overlay.showGrid(2,120,Novasol.Templates.parse('catalogue-order-success-template',viewModel));
			}
			else {
				Novasol.Overlay.showGrid(2,195,Novasol.Templates.parse('catalogue-order-fail-template',viewModel));
			}
		}

		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,348,$form);
		}

		function setDataFromNotes(data) {
			dataFromNotes = data;
		}


		$(function onDomReadyCatalogue(){
			$('#the-catalogue-list').delegate('li','click',onCatalogueClick);
		});

		Novasol.Catalogues = {
			setDataFromNotes: setDataFromNotes
		};

	})(jQuery);

}if(Novasol.context === "destinations_3") {

	(function mapOfEuropeClosure($, undefined){

		var $map, $list, isHidden=true, $overlay, $countryNameContainer, hideTimer, dataFromNotes;

		function setDataFromNotes(data) {
			dataFromNotes = data;
		}

		function preloadHighlightImages() {
			var urls= [];
			for(var i in dataFromNotes.productMarkets) {
				urls[urls.length] ='url(/site/redesign/img/maphilight_'+i+'.png)';
			}
			$(document.body).append('<style>body:after{content:'+urls.join(' ')+';display: none;}</style>');
		}

		function getOnMouseover(weAreHoveringTheMap) {
			return function onMouseover(e) {
				clearTimeout(hideTimer);
				var m = new Image(),$t = $(this.nodeName == 'A' ? this : this.parentNode), id = $t.attr('data-id');


				m.onload = function() {
					$overlay[0].src = m.src;
					if(isHidden) {
						isHidden = false;
						$overlay.show();
					}
					if(weAreHoveringTheMap) {
						$countryNameContainer
						.html(Novasol.Templates.parse('europemap-nameoverlay-template',{
							isoCode: id,
							name: dataFromNotes.productMarkets[id]
						}));
					}
				};
				m.src = '/site/redesign/img/mapHilight_'+id+'.png';
			}
		}

		function onMouseout(e) {
			hideTimer = setTimeout(function(){
				$countryNameContainer.empty();
				$overlay.hide();
				isHidden = true;
			},10);
		}

		$(function onDomReadyMapOfEurope(){
			var $m = $('#map-of-europe');
			$map = $m.find('div.map-of-europe')
			.on('mouseover','a span',getOnMouseover(true))
			.on('mouseleave', onMouseout);
			$list = $m.find('div.map-of-europe-country-list')
			.on('mouseover','a',getOnMouseover())
			.on('mouseout','a',onMouseout);
			$overlay = $map.find('img.overlay');
			preloadHighlightImages();
			$countryNameContainer = $map.find('.countryName');

		});

		Novasol.MapOfEurope = {
			setDataFromNotes: setDataFromNotes
		};

	})(jQuery);
}/** owner_contact_form.js **/
(function ownerContactFormClosure($, 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 calenderClosure($,undefined){

	var dataFromNotes;

	function createCalendar(newSettings){
		var settings,targetCurrentTime,height = 230;


		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;

		// Create message area (if any)
		var objMessages = null;
		if(settings.messages){
			objMessages = createCalendarMessages(settings.messages);
		}

		// The whole calendar is surrounded by a wrapper
		var html = "<div id=\""+settings.name+"\" class=\"nosoCalendar-wrapper\">";
		html += createInnerCalendarHTML(settings);
		if(objMessages){
			html += objMessages.html;
			height += objMessages.height+5;
		}
		html += "</div>";

		if(settings.inline){
			$(settings.target).append(html);
		}else{
			Novasol.Overlay.showHtml(298,height,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 createCalendarMessages(messages){
		try{
			var combinedHeight = 0;
			var html = ['<div id="nosoCalendar-messages" ##>'];
			if(messages.constructor != Array){
				messages = [messages];
			}
			for(var i=0, len=messages.length;i<len;i++){
				html[html.length] = '<div class="nosoCalendar-message">';
				html[html.length] = messages[i];
				html[html.length] = '</div>';
			}
			html[html.length] = '</div>';
			html = html.join('');
			$("body").append(html);
			combinedHeight = $("#nosoCalendar-messages").height();
			$("#nosoCalendar-messages").remove();
			html = html.replace(/##/, ['style="height:',combinedHeight,'px"'].join(''));
			return {
				height:combinedHeight,
				html: html
			}
		}catch(Exception){
			console.log(Exception);
			return "";
		}
	}

	function createInnerCalendarHTML(settings){
		var date = new Date(settings.currentDate),
		statusObject = {},
		currentDate,
		weekDay,
		selectable,
		i,
		previousStatus = "",
		newStatus = "",
		html = [],
		tempDate,
		currentMonth,
		weekInMonth = false,
		seasonCode,
		sysTexts = dataFromNotes.text;

		tempDate = new Date(date);
		tempDate.setDate(1);
		tempDate.setMonth(tempDate.getMonth()+settings.months);
		if(tempDate>settings.lastDate){
			date = new Date(settings.lastDate);
			date.setMonth(date.getMonth()-(settings.months-1));
		}

		currentDate = new Date(date);
		currentDate.setDate(1);

		for (var monthCount = 0, len = settings.months; monthCount < len; monthCount++) {

			currentMonth = 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[getDateAsString(currentDate)];
					html[html.length] = "<div class=\"nosoCalendar-weekday nosoCalendar-weekDay";
					html[html.length] = i;
					html[html.length] = "\">";
					if(weekDay!=currentDate.getDay() || currentDate.getMonth()!=currentMonth || 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;
						if(currentDate<settings.startDate){
							html[html.length] = "<div class=\"nosoCalendar-status nosoCalendar-status-na\" data-status=\"na\"></div>"; // Insert empty container
						}else{
							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){
		var convert = Novasol.Utils.convertAS400Date;
		if(settings.seasonCodes && currentDate){
			for(var x in settings.seasonCodes){
				var startDate = convert(settings.seasonCodes[x].from);
				var endDate = convert(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, lastDate = new Date(settings.lastDate);
			lastDate.setMonth(lastDate.getMonth()-(settings.months-1));

			id = settings.name+"-monthSelect";
			$("#"+id).remove();
			tempDate = new Date(settings.startDate);
			tempDate.setDate(1);
			html[html.length] = '<select name="monthSelect" id="';
			html[html.length] = id;
			html[html.length] = '" onchange="Novasol.calendar.calendars[\'';
			html[html.length] = settings.name;
			html[html.length] = '\'].setMonth(this.value)">';

			if(settings.preMonthOption) {
				html[html.length] = '<option value="';
				html[html.length] = settings.preMonthOption.value;
				html[html.length] = '">';
				html[html.length] = settings.preMonthOption.label;
				html[html.length] = '</option>';
			}

			while(tempDate<=lastDate){
				var selected = tempDate.getMonth()==settings.currentDate.getMonth() && tempDate.getFullYear() == settings.currentDate.getFullYear()?" selected=\"selected\"":"";
				html[html.length] = '<option value="';
				html[html.length] = tempDate.getTime();
				html[html.length] = '"';
				html[html.length] = selected;
				html[html.length] = '>';
				html[html.length] = sysTexts.month[tempDate.getMonth()];
				html[html.length] = ' ';
				html[html.length] = tempDate.getFullYear();
				html[html.length] = '</option>';
				tempDate.setMonth(tempDate.getMonth()+1);
			}

			if(settings.postMonthOption) {
				html[html.length] = '<option value="';
				html[html.length] = settings.postMonthOption.value;
				html[html.length] = '">';
				html[html.length] = settings.postMonthOption.label;
				html[html.length] = '</option>';
			}


			html[html.length] = "</select>";

			return html.join('');
		}
	}

	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){
		var dateOfMonth = ""+date.getDate(),
		monthOfYear = ""+(date.getMonth() + 1),
		fullYear = ""+date.getFullYear();
		return (dateOfMonth.length==1?"0":"") + dateOfMonth + "-" +
		(monthOfYear.length==1?"0":"") + monthOfYear + "-" +
		(fullYear);
	}

	function formatDisplayDate(date){
		var dateOfMonth = ""+date.getDate(),
		monthOfYear = ""+(date.getMonth() + 1),
		fullYear = ""+date.getFullYear();
		return dataFromNotes.text.shortWeekDay[date.getDay()] + " " +(dateOfMonth.length==1?"0":"") + dateOfMonth + "." +
		(monthOfYear.length==1?"0":"") + monthOfYear + "." +
		(fullYear);
	}

	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){
				updateMonth(settings, date);
			}
		}else{
			updateMonth(settings, date);
			return true;
		}
	}

	function handleCustomMonthOption(monthOption) {
		switch(monthOption.type) {
			case 'URL':
				location.href = monthOption.value;
				break;
			default:
				break;
		}
	}

	function updateMonth(settings, date){
		if(Object.prototype.toString.call(date)  != '[object Date]') {
			if(settings.postMonthOption && date === settings.postMonthOption.value) {
				handleCustomMonthOption(settings.postMonthOption);
				return;
			}
			else if(settings.preMonthOption && date === settings.preMonthOption.value) {
				handleCustomMonthOption(settings.preMonthOption);
				return;
			}
			else {
				date = new Date(1*date);
			}
		}
		var nextMonth = new Date(date);
		nextMonth.setMonth(nextMonth.getMonth()+1);
		if(nextMonth>settings.lastDate){
			date.setMonth(settings.lastDate.getMonth()-(settings.months-1));
		}
		if(date<settings.startDate){
			date.setMonth(settings.startDate.getMonth())
		}
		settings.currentDate = date;
		redrawCalendar(settings);
		settings.onMonthChange(date);
		/** Update month dropdown **/
		date.setDate(1);
		$("#"+settings.name+"-monthSelect").val(date.getTime());
	}

	function nextMonth(settings){
		return function (){
			var newDate = new Date(settings.currentDate);
			var finalDate = new Date(settings.lastDate);
			newDate.setMonth(newDate.getMonth()+1);
			newDate.setDate(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.getTime());
	}

	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 nextWeekday(weekday) {
		var date = new Date();
		var currentDay = date.getDay();
		date.setDate( date.getDate() + (weekday > currentDay ? ( weekday - currentDay ) : ( weekday + 7 - currentDay )) );
		return {
			date: date,
			formattedDate: formatDate(date)
			};
	}

	function setDataFromNotes(data) {
		dataFromNotes = data;
		Novasol.calendar.settings.showWeekNumbers = data.showWeekNumbers;
	}
	
	function getDateAsString(date){
		var month = date.getMonth()+1, day = date.getDate();
		return date.getFullYear()+(month<10?"0":"")+month+(day<10?"0":"")+day;
	}

	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 yyyyMMdd 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":"20120101","to":"20120108"}]
			onSelect:defaultOnSelect,
			onClose:defaultOnClose,
			onMonthChange:defaultOnMonthChange,
			messages: null
		},
		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,
			formatDisplayDate:formatDisplayDate,
			parseDateString:parseDateString,
			extractDataFromId:extractDataFromId,
			nextSaturdayFormatted:nextSaturdayFormatted,
			nextWeekday:nextWeekday
		}
	};


})(jQuery);/** jquery.placeholder.js **/
(function jqueryPlaceholderClosure($,undefined) {

	var className = 'has-active-placeholder',
	targetSelector = 'input[placeholder], textarea[placeholder]',
	nativeSupport = 'placeholder' in document.createElement('input');

	$.fn.placeholder = function () {
		if (nativeSupport) return this;
		var $elms = this.selector===targetSelector?this:this.find(targetSelector);

		var b = function() {
			if(this.value === '') {
				this.value = this.getAttribute('placeholder');
				$(this).addClass(className);
			}
			else if(this.value === this.getAttribute('placeholder')) {
				$(this).addClass(className);
			}
		};

		$elms.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')) {
				if(this.value==='') {
					this.value = this.getAttribute('placeholder');
				}
				else {
					$this.removeClass(className);
				}
			}
		});

		var i = $elms.length;
		while(i--) {
			b.apply($elms[i]);
		}

		$elms.closest('form:not(.'+className+')').addClass(className).submit(function onFormSubmit() {
			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);
				}
			}
		});

		return this;
	};

	if (!nativeSupport) {
		var origValFn = $.fn.val;

		$(function onDomReadyJqueryPlaceholder() {
			$(targetSelector).placeholder();
		});

		$.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 '';
				}
			}
			else if(arguments.length === 1 && arguments[0] === '') {
				var $elm = this.eq(0), elm = this[0];
				if(elm && $elm.hasClass(className)) {
					return origValFn.call(this, elm.getAttribute('placeholder'));
				}
			}
			return origValFn.apply(this, arguments);
		};
	}
})(jQuery);/** frontpage.js **/

if(Novasol.context === "homepage_0") {

	(function frontpageClosure($,undefined){

		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).html(cycleData[nextPictureSet].xlHeader);
			$mHeaders.eq(nextWrapper).html(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').click(function(){
				//not as redundant as it seems - ensures the actual href
				//is used if mousecursor stays over link when href changes
				location.href=this.href;
			});

			$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);

}/** quicksearch.js **/

(function quicksearchClosure($, undefined) {
	var config = {},
	cacheName = "quicksearch-settings",
	calendarMap = {},
	currentCountry,
	$forms = [],
	$elmsByClass = {},
	$elmsByName = {},
	$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 $form = $(this),
		country = $form.find('select.C').val(),
		houseNumberSearch = $form.attr("data-formtype"), // housenumbersearch
		action = "",
		productNumberContainer = $form.find("input[name='HQ']"),
		productNumbers = [];

		if (productNumberContainer.length) {
			$form.find("input.refnr").each(function (index, element) {
				var value = $(this).val();

				if (value !== "") {
					productNumbers.push(value.replace(" ",""));
				}
			});

			productNumberContainer.val(productNumbers.join(":"));
		}

		var numberOfPersonsCustomValue = $form.find("input[name='PE']").attr("data-customvalue");

		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
		$form.find("input[data-submitvalue='false']").removeAttr("name");

		// Quick fix to split guests into separate hidden input fields
		if (numberOfPersonsCustomValue && !productNumbers.length) {
			var splitNumberOfPersonsCustomValue = numberOfPersonsCustomValue.split("-");

			if (splitNumberOfPersonsCustomValue.length > 1) {
				$form.find("input[name='PE']").removeAttr("name");

				$forms.append(["<input type='hidden' name='PE' value='", splitNumberOfPersonsCustomValue[0], "' />"].join(""));
				$forms.append(["<input type='hidden' name='K' value='", splitNumberOfPersonsCustomValue[1], "' />"].join(""));
			}
		}

		if (houseNumberSearch == "housenumbersearch" && productNumbers.length == 1) {
			action = "/p/"+productNumbers[0];
		} else {
			action = "/r/"+(country || "000");
		}

		this.action = action;

		/* fix missing ED param for use in stats/tracking */
		$form.fixEDfieldBasedOnSDandDUR();

		return true;
	}

	function getOptionElement(name, value, selected) {
		if(!selected) {
			return '<option value="'+value+'">'+name+'</option>';
		}
		else {
			return '<option value="'+value+'" selected="selected">'+name+'</option>';
		}

	}
	/* seems to be unused code
	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, label, value, subareas, level) {
		if(level) {
			optionList[optionList.length] = getOptionElement('&nbsp; - '+label, value);
		}
		else {
			optionList[optionList.length] = getOptionElement(label, value);
			if(subareas) {
				subareas.sort(function (a, b) {
					return a[0] == b[0] ? 0 : (a[0] > b[0] ? 1 : -1);
				});

				for (var i = 0, subarea;subarea =  subareas[i]; i++) {
					generateOptionListForArea(optionList, subarea[0], subarea[1], undefined, 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) {
				//this function call will break if it ever happens
				updateDurationDropDown(previousValue);
			}
		});

		$("#quicksearch-duration div.col").delegate('a', 'click', function (event) {
			var $this = $(this);

			updateDurationDropDown($this.attr("data-value"), $this.text());

			Novasol.Overlay.hide();
		});
	}

	function updateDurationDropDown(value, text) {
		var $optGroup = $elmsByClass['DUR'].find("optgroup[name='olos']");

		$forms.find("input[name='DUR']").each(function() {
			$(this).val(value);
		});

		$optGroup.children("option[name!='altDur']").remove();

		$optGroup.prepend('<option value="'+value+'">'+text+'</option>');

		$elmsByClass['DUR'].val(value);

		saveState({
			name: "DUR",
			value: value,
			customValue: text
		});
	}

	function showSwitchDayOverlay(inputConfig) {
		var normalSwitchDay = config.normalSwitchDays[currentCountry];

		if (normalSwitchDay !== undefined && normalSwitchDay != inputConfig.selectedDay) {
			var overlay = $([inputConfig.overlaySelector, inputConfig.switchDayOverlaySelector].join(" "));
			var text = "";

			if (config.switchDayAlertExceptions[currentCountry]) {
				text = config.switchDayAlertExceptions[currentCountry];
			} else {
				text = config.switchDayAlertTemplate.replace("[XXX]", config.dateFullTexts[config.normalSwitchDays[currentCountry]]);
			}

			overlay.find("span.message").html(text);

			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 season = Novasol.SeasonList[$("select[name=C]").val()];
				var options = {
					target: containerSelector,
					inline: true,
					startDate: season.startDate,
					lastDate: 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 () {
					var $hiddenElement = $forms.find("input[name='SD']");
					var $visibleElement = $forms.find("input.SD");

					$hiddenElement.val("").attr("data-customvalue","");
					$visibleElement.val("").blur();

					onFormElementChange({
						target:$hiddenElement
					});

					closeCalendar(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 i, o, l,
		cachedSettings = getCacheSettings(),
		defaults = config.defaults,
		overwrites = config.overwrites || [],
		mergedState = cachedSettings.settings.slice(0),
		userStateEntries = {};

		for(i=0,o;o=mergedState[i];i++) {
			if(o.name) {
				userStateEntries[o.name] = i;
			}
		}

		for(i=0,o;o=defaults[i];i++) {
			if (userStateEntries[o.name] === undefined) {
				mergedState.push(o);
			}
		}

		for(i=0,o;o=overwrites[i];i++) {
			if (userStateEntries[o.name] === undefined) {
				mergedState.push(o);
			}
			else {
				mergedState[userStateEntries[o.name]] = o;
			}
		}
		var elms = $forms.children('input'),elmsByName={};
		for(i=0,l=elms.length;i<l;i++) {
			if(elmsByName[elms[i].name]) {
				elmsByName[elms[i].name] = elmsByName[elms[i].name].add(elms[i]);
			}
			else {
				elmsByName[elms[i].name] = elms.eq(i);
			}

		}

		for (var j = 0, elementState; elementState = mergedState[j]; j++) {
                        if (!elementState.name) {
                            continue;
                        }
			if(!$elmsByClass[elementState.name]) {
				$elmsByClass[elementState.name] = $forms.find("." + elementState.name);
			}
			var mainElement = $elmsByClass[elementState.name];
			var elementType = getElementType(mainElement);
			var dataContainerName = mainElement.attr("data-valuecontainername");

			if (dataContainerName !== undefined) {
				var hiddenInputField = elmsByName[dataContainerName];

				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);
				}
				if (elementState.name == "SD") {
					var dateSet = false;
					if (elementState.value != "") {
						var parsedDate = parseDate(elementState.value);

						if (parsedDate && parsedDate.getTime() > (new Date()).getTime()) {
							var arrivalDateCustomValue = formatDate(parsedDate);

							hiddenInputField.attr("data-customvalue", arrivalDateCustomValue);

							elementState.customValue = arrivalDateCustomValue;

							value = elementState.value;

							dateSet = true;
						}
					}

					if (!dateSet) {
						var nextSaturday = Novasol.calendar.functions.nextWeekday(6);

						elementState.customValue = formatDate(nextSaturday.date);
						value = nextSaturday.formattedDate;
					}
				}

				hiddenInputField.val(elementState.value = value);
			}

			switch (elementType) {
				case "SELECT":
					var foundElement, selector;

					if(!elementState.customValue) {
						selector = 'option[value="' + elementState.value + '"]';
					}
					else {
						selector = 'option[data-label="' +elementState.customValue + '"]';
					}
					foundElement = mainElement.find(selector).prop('selected', true).length > 0;

					if (elementState.name == "C") { // Quick fix to account for lack of update after setting attribute
						var selectedCountry = elementState.value;

						if (!foundElement) {
							selectedCountry = mainElement.find("option").eq(0).prop("selected", true).val();
						}

						var area = findStateObjectByName("R", mergedState);

						var data = {
							value: selectedCountry
						}

						if (area) {
							data.preselectedArea = area;
						}

						countryChanged(data);
					}
					else if (elementState.name == "DUR") {
						if (!foundElement) {
							updateDurationDropDown(elementState.value, elementState.customValue);
							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;
					}

					if (inputValue && inputValue != "") {
						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']":
					mainElement[0].checked = elementState.value == mainElement[0].value || elementState.value == 'checked';
					break;
			}
		}
	}

	function findStateObjectByName(name, mergedState) {
		for (var i = 0, o; o = mergedState[i]; i++) {
			if (o.name === name) {
				return o;
			}
		}
		return {};
	}

	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("nodeName");

		return tagName == "INPUT" ? "input[type='" + element[0].type + "']" : tagName;
	}

	function getElementValue(element) {
		var type = getElementType(element);
		var returnValue = {
			isCustom: false
		};

		switch (type) {
			case "SELECT":
				//this code will break if an option outside an optgroup is selected
				//if that cannot happen then the optgroup check is 100% useless overhead
				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[isoCode]) {
			var optionList = [getOptionElement(config.areaDefaultText, "")];
			if (config.areas[isoCode]) {
				var areas = config.areas[isoCode].areas;

				if (areas) {
					areas.sort(function areasSortFn(a, b) {
						return a[0] == b[0] ? 0 : a[0] > b[0] ? 1 : -1;
					});

					if (areas.length == 1) {
						optionList = [];
					}

					for (var i = 0, area; area= areas[i]; i++) {
						generateOptionListForArea(optionList, area[0],area[1],area[2], 0);
					}
				}
			}

			buildAreaList.cache[isoCode] = optionList;
		}

		return buildAreaList.cache[isoCode];
	}

	function countryChanged(data) {
		currentCountry = data.value;
		var preselectedArea = data.preselectedArea ? data.preselectedArea.value || false : false,
		optionList = buildAreaList(currentCountry);


		if (optionList.length > 0) {
			var html = optionList.join('');
			if(preselectedArea) {
				html.replace('value="'+preselectedArea+'"','value="'+preselectedArea+'" selected="selected"');
			}
			$elmsByClass['R'].empty().append(html);
		}
	}


	function init(inputConfig) {
		$quickSearchBox = $("#body").find("div.quicksearch-box");

		if (!$quickSearchBox.length) {
			return;
		}


		config = inputConfig;

		currentCountry = config.defaultCountry;

		$forms = $quickSearchBox.find("form");
		$overlays = $quickSearchBox.find("div.overlays");

		$elmsByClass['R'] = $forms.find("select.R");
		$elmsByClass['DUR'] = $forms.find("select.DUR");

		//add markup/text hidden for SEO purposes
		$overlays.find("div.quicksearch-numberofpersons").html(Novasol.Templates.parse('quicksearch-numberofpersons-template'));
		$elmsByClass['DUR'].append(Novasol.Templates.parse('quicksearch-duration-dropdown-template',{
			minNights:1
		}));

		// Handle tab clicks
		$quickSearchBox.find("div.tab-container").delegate('a', 'click', onTabClick);


		$elmsByClass['C'] =	$forms.find("select.C").change(function () { // Handle country<->area relation
			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
		$elmsByClass['PE'] = $forms.find("input.PE");
		var showGuestOverlayFunction = function (event) {
			showGuestOverlay(event, $elmsByClass['PE'])
		};

		$elmsByClass['PE'].bind('focus', {}, showGuestOverlayFunction);
		$forms.find("img.PE").bind('click', {}, showGuestOverlayFunction);

		var showCalendarFunction = showCalendar({
			hiddenInputSelector: "div.quicksearch-box form input[name='SD']",
			inputSelector: "div.quicksearch-box form input.SD",
			overlaySelector: "div.quicksearch-box .overlays",
			containerSelector: "div.quicksearch-arrivaldate",
			switchDayOverlaySelector: "div.quicksearch-switchday",
			name: "SD",
			season: config.seasonList
		});

		$elmsByClass['SD'] = $forms.find("input.SD").focus(showCalendarFunction);
		$forms.find("img.SD").click(showCalendarFunction);

		$elmsByClass['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") {
				$elmsByClass['DUR'].not($(this)).children("optgroup").children(["option[value='", selectedValue, "']"].join("")).prop("selected", true);
			} else {
				showDurationOverlay(previousDurationValue);

				return false;
			}

			previousDurationValue = selectedValue;
		});

		// 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);/** myfavourites.js **/

(function myFavoritesClosure($, 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, dataFromNotes;

	// Service functions
	function doPostSubmit(url, inputParameters) {
		inputParameters.type ="json";
		$.ajax({
			type: 'POST',
			url:url,
			data: inputParameters,
			error: function() {
				handleLoginFailure({
						e: inputParameters.email,
						p: inputParameters.password
					});
			},
			success: loginCompleted
		});


/*
	var $iframe = $('<iframe id="hejsa"/>').hide().load(function() {
			$(this).remove();
		}),
		form = $("<form />").attr({
			method: "post",
			action: url
		});
		inputParameters.type ="HTML";

		for (var parameter in inputParameters) {
			var value = inputParameters[parameter];

			if (value) {
				form.append($("<input />").attr({
					type: "hidden",
					"name": parameter,
					"value": value
				}));
			}
		}

		$(document.body).append($iframe);
		form.appendTo($iframe.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) {
			// Different separators needed for the search url than the one used internally
			var serializedProducts = (serializeProducts(favourites, ["id", "start", "end"]) || "").replace(/:/g,"|").replace(/;/g,":");

			// Converted dates
			//serializedProducts = serializedProducts.replace(/(\d{4})-(\d{2})-(\d{2})/g, function(str, p1, p2, p3, offset, s) { return [p3, p2, p1].join("-"); });

			document.location = [config.viewProductListBaseURL, serializedProducts, "&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");

			//@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();

			if (Novasol.SuperMenu !== "undefined" && Novasol.SuperMenu.isInitialized()) {
				superMenuLoaded();
			} else {
				$(document.body).bind("superMenuLoaded", function() {
					superMenuLoaded();
				});
			}

			$(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);
		}
	}

	function setDataFromNotes(data) {
		dataFromNotes = data;
	}

	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,
		setDataFromNotes: setDataFromNotes
	};

	/*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",
			safeBaseURL: dataFromNotes.safeBaseURL,
			baseURL: dataFromNotes.baseURL,
			presentationBaseURLTemplate: dataFromNotes.presentationBaseURLTemplate,
			viewProductListBaseURL: dataFromNotes.viewProductListBaseURL,
			brand: dataFromNotes.brand,
			salesmarket: dataFromNotes.salesmarket,
			defaultSearchCountry: dataFromNotes.defaultSearchCountry,
			defaultSearchBaseURL: dataFromNotes.defaultSearchBaseURL
		});
	});
})(jQuery);/** supermenu.js **/

(function supermenuClosure($,undefined){

	var hideTimeout, elmMenus, initialized = false;

	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(e) {
		e.preventDefault();
		var elm = $(this).focus();
		$(document.body).find('div.superMenuTop, div.superMenuBottom').hide();
		clearTimeout(hideTimeout);
		elm.data('superMenuTopContent').html(elm.html());
		elm.data('superMenuTop').show();
		elm.data('superMenuBottom').show();
	}

	function onSuperMenuOver(){
		clearTimeout(hideTimeout);
	}

	function onSuperMenuOut() {
		hideTimeout = setTimeout(function(){
			$(document.body).find('div.superMenuTop,div.superMenuBottom').hide();
		},50);
	}



	$.fn.extend({
		superMenu: function() {
			var elm,templateId,lsw,pos,elmsToAdd = [];

			for(var i=0,l=this.length;i<l;i++) {

				elm = this.eq(i);
				templateId = elm.data('supermenuid');
				lsw = elm.outerWidth()-2;
				pos = elm.offset();
				elm.data('superMenuTop',
					$(
						'<div class="superMenuTop" style="top: '+(pos.top-11)+'px; left: '+(pos.left-15)+'px; width: '+(elm.outerWidth()+30)+'px">'+
						'<div class="left"></div>'+
						'<div class="middle"><a href="'+elm.prop('href')+'">'+elm.html()+'</a></div>'+
						'<div class="right"></div>'+
						'</div>'
					)
				);
				elm.data('superMenuBottom',
					$(
						'<div class="superMenuBottom" style="top: '+(pos.top+29-11)+'px; left: '+(pos.left-44-19)+'px">'+
						'<div class="left"></div>'+
						'<div class="leftSpacer" style="width: '+lsw+'px"></div>'+
						'<div class="middle" style="left: '+(64+lsw)+'px"></div>'+
						'<div class="rightSpacer" style="left: '+(64+lsw+18)+'px"></div>'+
						'<div class="right"></div>'+
						'<div class="content">'+Novasol.Templates.parse(templateId)+'</div>'+
						'</div>'
					)
				);


				elm.on({
					'click mouseover': onSuperMenuAnchorOver,
					'mouseleave': onSuperMenuOut
				})
				.data('superMenuTopContent',elm.data('superMenuTop').find('div.middle a'))

				elmsToAdd.push(elm.data('superMenuTop'),elm.data('superMenuBottom'));
			}
			jQuery.fn.append.apply($(document.body),elmsToAdd);
			return this;
		}
	});

	function isInitialized() {
		return initialized;
	}

	Novasol.SuperMenu = {
		isInitialized: isInitialized
	}

	Novasol.ready(function onDomReadySupermenu(){
		elmMenus = $('#menu a').filter(function(){
			return !!document.getElementById($(this).data('supermenuid'));
		});

		elmMenus.superMenu();

		initialized = true;

		$(document.body)
		.on('mouseenter','div.superMenuTop,div.superMenuBottom',onSuperMenuOver)
		.on('mouseleave','div.superMenuTop,div.superMenuBottom',onSuperMenuOut)
		.trigger("superMenuLoaded");
	});
	$(window).resize(onWindowResize);

})(jQuery);/** search.js **/

if(Novasol.context === "searchresults_") {

	(function searchClosure($,undefined) {

		//	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 );
		};

		$( window ).load( function onWindowLoadSearch() {

			$('#layout-picker a').click( layoutPicker );
		});
	})(jQuery);

}/** search-filters.js **/

if(Novasol.context === "searchresults_") {
	(function searchFiltersClosure($, undefined) {

		var $form, filterCategories,	groupstateInput, durationSelector, initDurVal, dataFromNotes;

		function setDataFromNotes(data) {
			dataFromNotes = data;
		}

		function onSearchSubmit(e) {
			/* fix missing ED param for use in stats/tracking */
			$form.fixEDfieldBasedOnSDandDUR();
		}

		//	Form elements
		function submitCriteria(e){
			var country = $form.find("select[name=C]").val(), elmCurrentArea, $this = $(this), areas = $form.find("select[name^='AREA']");

			if ($this.attr("id") == "AREA_0") {
				$form.find("select[name='AREA_1']").val("");
				$("#R").val($this.val());
			} else if($this.attr("id") && $this.attr("id").indexOf("AREA")>-1){

				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("");
				}
			}else if($this.attr("id")=="Q20"){
				if(!$this.is(":checked")){
					$form.append('<input type="hidden" name="Q20" value="N" />')
				}
			}

			if($form.data("country")!=country){
				$form.attr("action","/r/"+country);
				areas.append('<option value=""></option>').val("");
				$("#R").val("");
			}
			$form.submit();
		}

		function openDatePicker(e){
			var country = $("form#search select[name=C]").val(), season = Novasol.SeasonList[country];
			var options = {
				target: 'input[name="SD"]',
				onSelect: submitCriteria,
				startDate: season.startDate,
				lastDate: season.endDate
			};

			if (country && dataFromNotes && dataFromNotes.switchDayMessageMap) {
				var switchDayMessage = dataFromNotes.switchDayMessageMap[country];

				if (switchDayMessage) {
					options.messages = switchDayMessage;
				}
			}

			Novasol.calendar.create(options);
		}

		//	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').toggleClass('collapse-all',$.inArray('c',states) != -1);
		}

		//	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).data('key');
			var newLocation = Novasol.Utils.updateQueryString(location.search, key, '');
			newLocation = Novasol.Utils.updateQueryString(newLocation, 'OF', '')
			if (key=='AREA_0') {
				newLocation = Novasol.Utils.updateQueryString(newLocation, 'R', '');
				newLocation = Novasol.Utils.updateQueryString(newLocation, 'AREA_1', '');
			} else if (key=='AREA_1') {
				newLocation = Novasol.Utils.updateQueryString(newLocation, 'R', Novasol.Utils.getParameterByName(newLocation, 'AREA_0'));
			}
			location = newLocation;
		}

		//	Clear all search criteria
		function clearAllActiveCriteria(e){
			e.preventDefault();
			var url = location.search;
			$(this).siblings('span').each(function (i, el){
				var key = $(el).data('key');
				url = Novasol.Utils.updateQueryString(url, key, '');
			});
			location = url;
		}

		function initDurationSelector() {
			durationSelector = $('select[name="DUR"]');
			if(durationSelector.length==0){
				return;
			}
			initDurVal = 1*durationSelector.data("default");
			durationSelector
			.html(Novasol.Templates.parse('quicksearch-duration-dropdown-template',{
				minNights:1,
				duration: initDurVal
			}))
			.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);
			}
		}

		//	onDOMready fns
		$(function onDomReadyFilters() {
			$form = $('#search').on('submit',onSearchSubmit);
			filterCategories = $form.children('div.filter-category');
			groupstateInput = $('input[name="groupstate"]');
			if(groupstateInput.length>0){
				setCategories();
			}
			initDurationSelector();
			$('input.datepicker-active[disabled!=disabled]').focus(openDatePicker).next('img').click(openDatePicker);
			$('#toggle-all-categories').click(toggleAllCategories);
			filterCategories
			.on('change', 'select, input', submitCriteria)
			.on('click', 'a.toggler',toggleCategory);
			$('#active-search-criteria')
			.on('click','span',clearActiveCriteria)
			.on('click','a.functionality', clearAllActiveCriteria);
			updateCategories();
		});

		Novasol.SearchFilters = {
			setDataFromNotes: setDataFromNotes
		};

	})(jQuery);

}
/** search-map.js **/
/*
 * @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:
 *	}]
 */

if(Novasol.context === "searchresults_" && typeof getMapSearchData === 'function') {

	(function searchMapClosure($,undefined) {
		var map, mapOptions, fMapBounds, propertyBox, propertyBoxDefaults, icons = {}, mapSearchData = getMapSearchData();

		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 );
			$.bindOutsideClick('#search-result-map',closePropertyBox);
		}

		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 = Novasol.Templates.parse('mapProductoverlayTemplate',data);
			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: '314px',
					height: '215px'
				},
				boxClass: 'product-infoBox',
				closeBoxURL: '',
				infoBoxClearance: new google.maps.Size( 1, 1 ),
				isHidden: false,
				pane: 'floatPane',
				enableEventPropagation: true
			};

			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 );
			$(".product-infoBox").on( 'click', 'button', closePropertyBox );

			fMapBounds = new google.maps.LatLngBounds();

			for (var i=0,product;product=mapSearchData.products[i];i++) {
				addPropertyToMap(product);
			}

			if (mapSearchData.infoPanelTxt != "") {
				var infoPanel = document.createElement( 'DIV' );
				infoPanel.className = 'product-infoPanel low-prio-copy';
				infoPanel.innerHTML = mapSearchData.infoPanelTxt;

				infoPanel.index = 1;
				map.controls[ google.maps.ControlPosition.TOP_RIGHT ].push( infoPanel );
			}

			centerMap();
		}

		$.getScript('/site/redesign/js/google.maps.infobox.js',initialize);

	})(jQuery);

}/** house.js **/

if(Novasol.context === "showhouse_") {
	(function houseClosure(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.calendar.currentDate || house.availability.selectedDate),
			dur = house.calendar.settings?house.calendar.settings.duration:house.calendar.duration,
			endDate = new Date((new Date(startDate)).setDate(startDate.getDate() + dur)),
			adults = $("select[name=PE]").val(),
			children = $("select[name=K]").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,"&NP=",pets,
				"&A=",$.cookie('Agency') || '',
				"&F=",$.cookie('F') || '',
				"&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.replace("http://",""),
				"&wt_si_n=",house.trackingPath
			].join('');
		}

		function onRequestValidationSuccess() {
			var iso = $(this).find("select[name=country]").val();
			$(this).find("input[name=countryname]").val($(this).find("option[value="+iso+"]").text());
			var data = $(this).serialize();
			Novasol.Overlay.showHtml(200,100,Novasol.Systext.house_requestform_loading_message||"Loading...");
			$.post('/HouseRequest',data,function(reply){
				Novasol.Overlay.showHtml(200,100,reply);
			},'text');
		}

		function onShowRequestClick(e){
			e.preventDefault();
			var house = Novasol.house,
			startDate = new Date(house.calendar.currentDate || house.availability.selectedDate),
			dur = house.calendar.settings?house.calendar.settings.duration:house.calendar.duration,
			endDate = new Date((new Date(startDate)).setDate(startDate.getDate() + dur)),
			showBankDetails = dataFromNotes.requestViewData && dataFromNotes.requestViewData.showBankDetails,
			viewData = {
				showBankDetails: showBankDetails,
				h: house.id,
				sd: Novasol.calendar.functions.formatDate(startDate),
				ed: Novasol.calendar.functions.formatDate(endDate),
				pe: $("select[name=PE]").val(),
				k: $("select[name=K]").val(),
				np: $("select[name=np]").val() || "",
				p:$('#house-price-box .finalPrice .price').text(),
				a:$.cookie("Agency") || ""
			};
			Novasol.Overlay.showGrid(3,100,Novasol.Systext.house_requestform_loading_message||"Loading...");
			$.get("/HouseRequest",viewData,function(reply){
				Novasol.Overlay.showGrid(3,showBankDetails?680:500,reply);
				$('#house-request-form').bind('validation-success',onRequestValidationSuccess);
			},'text');			
		}

		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('.show-request','click',onShowRequestClick)
			.delegate('.go-to-calender-and-prices','click',onGoToCalenderAndPricesClick);

			$('#house-bookingInformation').delegate(".functionality","click",function(e){
				e.preventDefault();
				$(this).next("ul").toggle();
			});

			$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_tabs.js **/

if(Novasol.context === "showhouse_") {

	(function houseTabsClosure($,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;
				var elmSeasonChangeLinks = $("#price-tab-content .house-changeSeason");
				for(var i=0,len=elmSeasonChangeLinks.length,elm;i<len;i++){
					elm = elmSeasonChangeLinks.eq(i);
					elm.append(": "+getSeasonRangeStringForSeason(elm.data("season")));
				}
				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.onDateSelect,
					preMonthOption: Novasol.house.calendar.preMonthOption,
					postMonthOption: Novasol.house.calendar.postMonthOption
				});
				$("#monthContainer").html(Novasol.house.calendar.getMonthDropDownHTML());
				availability.init();
				availability.load(Novasol.house.calendar);
			}
		}

		function getSeasonRangeStringForSeason(season){
			var fullSeason = Novasol.SeasonList[Novasol.house.country],
			seasonRangeString = "";
			if(fullSeason){
				if(season<Novasol.house.calendar.startDate.getFullYear()) {
					seasonRangeString += Novasol.calendar.functions.formatDisplayDate(fullSeason.startDate) +
					" - " +
					Novasol.calendar.functions.formatDisplayDate(Novasol.house.calendar.startDate);
				}else{
					seasonRangeString += Novasol.calendar.functions.formatDisplayDate(Novasol.house.calendar.endDate) +
					" - " +
					Novasol.calendar.functions.formatDisplayDate(fullSeason.endDate);
				}
			}
			return seasonRangeString;
		}

		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 houseGalleryClosure($, 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());
			});
			$(document).keydown(function(e){
				if(e.which=='37'){
					e.preventDefault();
					setLargeImageByNumber(getPrevPictureID());
				}else if(e.which=='39'){
					e.preventDefault();
					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 houseAvailabilityClosure($,undefined){

		var $housePeriods,$houseOffers,selectedPeriodId, selectedPeriodTs, 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,
			onDateSelect:onDateSelect
		};

		function setDataFromNotes(data){
			dataFromNotes = data;
		}

		function initAvailability(){
			$housePeriods = $('#house-periods');
			$houseOffers = $('#house-offers');
			var house = Novasol.house;
			var duration = house.calendar.duration || house.calendar.settings.duration;
			$('#price-tab-content')
			.find("select[name=PE],select[name=K],select[name=np],select[name=ni]")
			.change(updateWithGuestsAndPeriods)
			.end()
			.find('select[name="DUR"]')
			.html(Novasol.Templates.parse('quicksearch-duration-dropdown-template',{
				minNights:1,
				duration:duration
			}))
			.val(duration)
			.change(onDurationChange);

			if(house.selectedDate){
				house.availability.selectedDate = house.selectedDate;
			}

			$("#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();
			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.onDateSelect(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();
			});



			$("#"+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[name=altDur]');
			/*var $selectBox = $('select[name="DUR"]');*/
			/*$selectBox.find("optgroup[name='olos']").append('<option id="custom-duration" value="'+val+'">'+txt+'</option>');*/
			$('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() {
			$("#house-messages .availabilityMessage.house-error").remove();
			if($(this).val()) {
				updateWithGuestsAndPeriods();
			}
			else {
				Novasol.Overlay.showHtml(615,340,Novasol.Templates.parse('quicksearch-duration-template'), onCustomDurationSelectionHide);
				$('#quicksearch-duration').delegate('a', 'click',onCustomDurationSelection);
			}
		}

		function loadAvailabilityForCalendar(calendar){
			var people = 1*$("select[name='PE']").val() + 1*$("select[name='K']").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;
			if(startDate<calendar.settings.currentDate){
				startDate = new Date(calendar.settings.currentDate);
			}
			startDate.setDate(1);
			if(startDate<now){
				startDate = now;
			}
			if(startDate<calendar.settings.startDate){
				startDate = new Date(calendar.settings.startDate);
			}
			endDate = new Date(startDate);
			endDate.setMonth(endDate.getMonth()+calendar.settings.months);
			endDate.setDate(1);
			endDate.setDate(endDate.getDate()-1);
			if(endDate>calendar.settings.lastDate){
				endDate = new Date(calendar.settings.lastDate);
			}
			startDateString = Novasol.calendar.functions.formatDate(startDate);
			endDateString = Novasol.calendar.functions.formatDate(endDate);

			params = {
				com:dataFromNotes.sitecode,
				l:dataFromNotes.language,
				h:Novasol.house.id,
				s:startDate.getFullYear(),
				na:people,
				dur:duration,
				sd:startDateString,
				ed:endDateString,
				reload:reload,
				"noCache": (new Date()).getTime()
			};

			$housePeriods.html("");
			$('#'+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 house = Novasol.house, calendar = house.calendar, availability = house.availability, settings = calendar.settings;
			var redraw = false;
			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){
				calendar.redraw(settings);
			}
			if(ajaxData.messages.length>0){
				setAvailabilityMessages(ajaxData.messages);
			}
			markArrivalDates(ajaxData.periods);
			setPeriods(ajaxData.periods);
			setConcepts(ajaxData.conceptPeriods);
			if(availability.selectedDate && $("#"+settings.name+"-"+availability.selectedDate.getTime()).hasClass("selectable")){
				loadBookingInformationForDateElm(null, availability.selectedDate);
			}
		}
		
		function setAvailabilityMessages(messages){
			var elmMessages = $("#house-messages");
			elmMessages.find(".availabilityMessage").remove();
			elmMessages.append(Novasol.Templates.parse('availability_message_template',{
				messages:messages
			}));
			elmMessages.find(".availabilityMessage").yellowFade();
		}

		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(allowRenderingOfNonSelectedRow) {
			var av = Novasol.house.availability, periods = $housePeriods.parent().data('periodsCache'), convert = Novasol.Utils.convertAS400Date;
			if(!allowRenderingOfNonSelectedRow) {
				for(var i=0,period;period=periods[i];i++) {
					if(convert(period.sd).getTime()==selectedPeriodTs) {
						av.rowOffset=Math.floor(i/av.rowsToShow) * av.rowsToShow;
						break;
					}
				}
			}
			$housePeriods.html(Novasol.Templates.parse('period-table-template', {
				selectPeriodTs: selectedPeriodTs,
				periods: periods.slice(av.rowOffset,av.rowOffset+av.rowsToShow),
				type: 'period-row'
			}));
			$("#next-period-rows").toggle(periods.length > av.rowOffset+av.rowsToShow);
			$("#prev-period-rows").toggle(av.rowOffset > 0);
		}

		function setPeriods(periods){
			var cachedPeriods = periods.slice(0);
			$housePeriods.parent()
			.data('periodsCache',cachedPeriods)
			.data('render',renderPeriods);
			renderPeriods();
		}

		function goToNextOffset(e){
			e.preventDefault();
			var av = Novasol.house.availability;
			av.rowOffset += av.rowsToShow;
			renderPeriods(true);
		}

		function goToPrevOffset(e){
			e.preventDefault();
			var av = Novasol.house.availability;
			av.rowOffset = av.rowOffset <= av.rowsToShow ? 0 : av.rowOffset -av.rowsToShow;
			renderPeriods(true);
		}


		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,house = Novasol.house;
			for(var key in conceptPeriods){
				html = "";
				concepts = conceptPeriods[key];
				for(var x in concepts){
					html += house.availability.conceptTemplate
					.replace(/%src%/ig,concepts[x].img)
					.replace(/%alt%/ig,concepts[x].name)
					.replace(/%title%/ig,concepts[x].name);
				}
				elmMonth = $("#"+house.calendar.settings.name+"-"+Novasol.Utils.convertAS400Date(key).getTime()).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+"-"+Novasol.Utils.convertAS400Date(period.sd).getTime();
			}
			$(ids.join(',')).addClass("selectable");
		}
		
		function onDateSelect(elmDate,date){
			var house = Novasol.house, calendar = house.calendar;
			var endDate = new Date(date);
			endDate.setDate(endDate.getDate()+calendar.settings.duration);
			if(endDate.getMonth()>calendar.settings.currentDate.getMonth()+(calendar.settings.months-1)){
				var monthDate = new Date(date);
				monthDate.setDate(1);
				calendar.setMonth(monthDate);
			}
			loadBookingInformationForDateElm(elmDate,date);
		}

		function loadBookingInformationForDateElm(elmDate,date){
			var cachedPeriods = $housePeriods.parent().data('periodsCache'),ts = date.getTime(), convert = Novasol.Utils.convertAS400Date;
			var house = Novasol.house, calendar = house.calendar;
			for(var i=0,period;period = cachedPeriods[i];i++) {
				if(convert(period.sd).getTime() == ts) {
					var $loading = $('<div class="loading-overlay"><img src="/site/redesign/img/loading.gif"/></div>').appendTo('#house-offers-wrapper, #house-bookingInformation');
					var params = {
						"dur":calendar.settings.duration,
						"pe":$("select[name='PE']").val(),
						"k":$("select[name='K']").val(),
						"ni":$("select[name='ni']").val(),
						"np":$("select[name='np']").val(),
						"s":house.season,
						"com":dataFromNotes.sitecode,
						"l":dataFromNotes.language,
						"h":house.id,
						"sd":Novasol.calendar.functions.formatDate(date),
						"request": period.request,
						"noCache": (new Date()).getTime()
					};
					house.availability.selectedDate = new Date(date);
					markPeriodAsSelected(date);
					updateFavDates(date);
					$.post(dataFromNotes.bookingInformationPath,params,function(reply){
						var elm = $("#house-bookingInformation");
						elm.html(reply);
						$housePeriods.parent().data('render')();
						updateBookingInformationPosition();
						$loading.remove();
					},"text");
					break;
				}
			}
			calendar.markDatesAsSelected(date,calendar.settings.duration);
		}

		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',Novasol.calendar.functions.formatDate(date))
			.data('end',Novasol.calendar.functions.formatDate(edDate));
		}

		function markPeriodAsSelected(date){
			$(".period-row").removeClass("selected");
			selectedPeriodId = null;
			if(date){
				selectedPeriodTs = date.getTime();
				selectedPeriodId = "#period-row-"+selectedPeriodTs;
				$(selectedPeriodId).addClass("selected");
			}
		}

		function updateWithGuestsAndPeriods(){
			var adults, children, elmBookingInformationParent, href;
			adults = 1*$("select[name='PE']").val();
			children = 1*$("select[name='K']").val();
			var elmNewSeasonLinks = $(".house-changeSeason");
			for(var i=0,len=elmNewSeasonLinks.length,elm;i<len;i++){
				elm = elmNewSeasonLinks.eq(i);
				href = elm.attr("href")
				.replace(/#.*/ig,'')
				.replace(/PE=[^&]*/ig,'')
				.replace(/K=[^&]*/ig,'')
				.replace(/DUR=[^&]*/ig,'')
				.replace(/np=[^&]*/ig,'')
				.replace(/&&/g,'');
				elm.attr('href',[href,
					'&PE=',
					adults,
					'&K=',
					children,
					'&np=',
					$("select[name=np]").val()||'',
					'&DUR=',
					$("select[name=DUR]").val(),
					'#price-tab'
					].join(''));
			}

			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){
					loadBookingInformationForDateElm(null,new Date(1*$("#period-row-"+Novasol.house.availability.selectedDate.getTime()).data("id")));
				}
			}
		}

		function updateBookingInformationPosition(){
			if(!$('#price-tab-content').hasClass('active') || $('html').hasClass('ie7') || $('html').hasClass('ie8')){
				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_map.js **/

if(Novasol.context === "showhouse_") {
	(function houseMapClosure($, undefined){

		var map,mapIsLoaded;

		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,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			if(Novasol.house.geoQuality<=6 || Novasol.house.zoomPermission=="n") {
				mapOptions.maxZoom = 11;
				mapOptions.minZoom = 4;
				mapOptions.streetViewControl = false;
			}

			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() {
			if(mapIsLoaded) {return;}
			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);
			mapIsLoaded=true;
		}

		$(function onDomReadyHouseMap(){
			if(!document.getElementById('house-top')) {
				return;
			}

			if(location.href.indexOf('#map-tab') != -1) {
				loadGoogleMap();
			}

			$("#map-tab").click(function(){
				loadGoogleMap();
//				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 houseSendToFriendClosure($,undefined) {
		var form, feedback, dataFromNotes;

		function sendToFriend() {
			var data = $( '#email-overlay' ).data();

			Novasol.Overlay.showHtml( data.width, data.height, Novasol.Templates.parse('email-overlay'));

			form = $( 'form.email-overlay' ).placeholder();
			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 );
		}

		$(function onDomReadySendToFriend() {
			$('#send-to-friend').click(sendToFriend);
		});

		Novasol.house.SendToFriend = {
			setDataFromNotes: function(data) { dataFromNotes=data}
		};

	})(jQuery);
}/** house_social.js **/

if(Novasol.context === "showhouse_") {

	(function houseSocialClosure($,undefined) {
		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';
					document.body.appendChild(po);
				})();
			}

			/* 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';
					document.body.appendChild(sc);
				})();
			}
		}

		function openSocialOverlay() {
			var html = $('#social-overlay-tmpl').html().replace(/^\s*<!--|-->\s*$/g,'');
			Novasol.Overlay.showHtml( 220, 220, html );
			activateLinks();
		}

		$(function onDomReadyHouseSocial() {
			$('a.moreSocial').click(openSocialOverlay);
			$('#facebook-share').click(function(e){
				Novasol.Webtrends.dcsMultiTrack(
					'DCS.dcsuri', '/HousePresentation_SocialMediaShare',
					'WT.ti', 'HousePresentation_SocialMediaShare',
					'DCSext.socialtype', 'Share',
					'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',''
				);
				if(!e.ctrlKey) {
					e.preventDefault();
					var height = 600,
							width=980,
							posX= (window.screen.width-width)/2,
							posY = (window.screen.height-height)/2;
					var w = window.open(this.href,'FBOverlay','height='+height+',width='+width+',left='+posX+',top='+posY);
				}
			});
		});

	})(jQuery);

};(function chatClosure($,undefined){

	var oldWrite, dataFromNotes;

	function ourWrite(str) {
		$('<span>'+dataFromNotes.chatSysText+'</span>').click(new Function('event',$(str).attr('onclick'))).appendTo('#chat-link-container');
		$(document.body).append('<div style="display: none;" id="actual-chat-link">'+str+'</div>');
		document.write = oldWrite;
	}

	$(window).load(function onWindowLoadChat(){
		if(dataFromNotes && dataFromNotes.siteId && dataFromNotes.planId) {
			setTimeout(function(){
				oldWrite = document.write;
				document.write = ourWrite;
				$(document.body).append(
					'<script src="//chatserver.comm100.com/js/LiveChat.js'+
					'?siteId='+dataFromNotes.siteId+
					'&amp;planId='+dataFromNotes.planId+
					'&amp;partnerId=-1" type="text/javascript"></script>'+
					'<script type="text/javascript" src="//chatserver.comm100.com/ChatButton.aspx'+
					'?siteId='+dataFromNotes.siteId+
					'&amp;planId='+dataFromNotes.planId+
					'&amp;partnerId=-1"></script>'
				);
			},10);
		}
	});

	Novasol.Chat = {
		setDataFromNotes: function(data) { dataFromNotes = data;}
	};

})(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 webtrendsClosure($, undefined) {

	var dataFromNotes, webTrendsInstance;

	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&&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 && 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 && 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 webTrendsInstance !== "undefined"){
			return webTrendsInstance.dcsMultiTrack.apply(webTrendsInstance,arguments);
		}
	}

	$(window).load(function onWindowLoadWebtrends(){
		setTimeout(function(){
			webTrendsInstance = new WebTrends(dataFromNotes.trackingId);
			webTrendsInstance.dcsGetId(function(){
				webTrendsInstance.dcsCollect();
			});
		},10);
	});

	Novasol.Webtrends = {
		setDataFromNotes: function(data) {
			dataFromNotes = data;
		},
		dcsMultiTrack: dcsMultiTrack,
		exposeData: function(){
			var data = {};
			for(var i in webTrendsInstance) {
				if(Object.prototype.toString.call(webTrendsInstance[i])!='[object Function]'){
					data[i] = webTrendsInstance[i];
				}
			}
			return data;
		}
	};

})(jQuery);

function dcsMultiTrack(){
	Novasol.Webtrends.dcsMultiTrack.apply(this,arguments);
}


if(Novasol.context === "bookshow_") {

	(function($,undefined){

		function onLinkMousedown(e) {
			var path = $(this).attr('href');
			if(/^\/[^\/]/.test(path)) {
				this.href=Novasol.deploydomain+path;
			}
		}

		$(function(){
			$(document.body).on('mousedown','#header a, #menu a, #footer a, #overlay a, .superMenuBottom a, .superMenuTop a', onLinkMousedown);
		});

	})(jQuery);

}
