﻿
(function(){if(typeof BA==='undefined'){BA={};}
if(typeof BA.Flat==='undefined'){BA.Flat={};}
if(typeof BA.Flat.AjaxBookingCalculator==='undefined'){BA.Flat.AjaxBookingCalculator={};}
var stringToXmlDocument=function(text)
{var doc;if(window.ActiveXObject)
{doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(text);}else
{var parser=new DOMParser();doc=parser.parseFromString(text,'text/xml');}
return doc;};var getNbDaysBetween=function(date1,date2)
{var oneDay=1000*60*60*24;var date1InMs=date1.getTime();var date2InMs=date2.getTime();var differenceMs=Math.abs(date1InMs-date2InMs);return Math.round(differenceMs/oneDay);};var timeStampToDate=function(xmlDate)
{var dt=new Date();var dtS=xmlDate.slice(xmlDate.indexOf('T')+1,xmlDate.indexOf('.'));var TimeArray=dtS.split(":");dt.setUTCHours(TimeArray[0],TimeArray[1],TimeArray[2]);dtS=xmlDate.slice(0,xmlDate.indexOf('T'));TimeArray=dtS.split("-");dt.setUTCFullYear(TimeArray[0],TimeArray[1]-1,TimeArray[2]);return dt;};var loader={};Cuke.apply(loader,{wrapper:null,addTo:function(container)
{this.wrapper=$j("<div class='ba-loader'>"+"<div>"+Cuke.getString("Cuke.Loading")+"</div>"+"<img src='"+Cuke.skin+"img/ajax-loader-beapart-transparent.gif' alt='"+Cuke.getString("Cuke.Loading")+"'/>"+"</div>").appendTo(container).height(container.height()).width(container.width());},remove:function()
{this.wrapper.fadeOut(400,function(){$j(this).remove();});}});Cuke.apply(BA.Flat.AjaxBookingCalculator,{priceDetails:{allCurrency:{},currentCurrency:null,wrapper:null,priceContainer:null,templateWithDiscount:"",templateWithoutDiscount:"",calculator:null,init:function(wrapper,defaultCurrency,calculator,templateWithDiscount,templateWithoutDiscount)
{var self=this;this.wrapper=wrapper.css({position:"relative"});this.calculator=calculator;this.templateWithDiscount=templateWithDiscount;this.templateWithoutDiscount=templateWithoutDiscount;this.priceContainer=$j('.price-container',this.wrapper).css({position:"relative"});this.allCurrency[""+defaultCurrency.Currency]=defaultCurrency;this.currentCurrency=defaultCurrency;$j('.currency .control',this.wrapper).change(function()
{var id=$j(this).val();var currency=self.allCurrency[id];if(currency)
{self.currentCurrency=currency;self.update();}
else
{loader.addTo(self.priceContainer);$j.ajax({type:"POST",contentType:"application/json; charset=utf-8",url:Cuke.RootUrl+"BeApart/Basic/Service/CurrencyService.asmx/GetRateFromEuropeanCentralBank",data:JSON.stringify({currencyResId:id}),dataType:"json",success:function(resp)
{if(resp.d.Result===0)
{currency=resp.d.Data;self.allCurrency[id]=currency;self.currentCurrency=currency;self.update();}
else{alert(resp.d.ErrorText);}
loader.remove();}});}});$j(".bookButton",this.wrapper).click(function()
{var paymentPageUrl=$j(this).attr("href");loader.addTo(self.wrapper);self.calculator.isAvailable(function(data)
{if(data.Xml===null)
{$j.ajax({type:"POST",contentType:"application/json; charset=utf-8",url:Cuke.RootUrl+"BeApart/Basic/Service/BookingService.asmx/CreateTempBooking",data:JSON.stringify({flatId:self.calculator.flat.FlatID}),dataType:"json",success:function(resp)
{if(resp.d.Result===0)
{window.location.href=paymentPageUrl;loader.remove();}
else{alert(resp.d.ErrorText);}}});}
else
{self.hide();}});return false;});},update:function()
{var self=this;this.priceContainer.height(this.priceContainer.height());this.priceContainer.children(":visible:not(.ba-loader)").remove();var priceInfo=this.calculator.flat.PriceInfo;var rate=this.currentCurrency.Rate;var html;var nbDays=getNbDaysBetween(this.calculator.calendarTo.selected[0],this.calculator.calendarFrom.selected[0]);if(priceInfo!==null&&priceInfo.Discount>0)
{html=Cuke.format(this.templateWithDiscount,this.currentCurrency.Symbol,nbDays,(parseInt(priceInfo.TotalFinalPrice*rate,10)/100).toFixed(2),(parseInt(priceInfo.TotalFinalPrice*rate/nbDays,10)/100).toFixed(2),(parseInt(priceInfo.TotalFinalFee*rate,10)/100).toFixed(2),(parseInt((priceInfo.TotalFinalPrice-priceInfo.TotalFinalFee)*rate,10)/100).toFixed(2),(parseInt(priceInfo.TotalPriceBefore*rate,10)/100).toFixed(2),(parseInt((priceInfo.TotalPriceBefore-priceInfo.TotalFinalPrice)*rate,10)/100).toFixed(2),(priceInfo.Discount/100).toFixed(2));}
else
{html=Cuke.format(this.templateWithoutDiscount,this.currentCurrency.Symbol,nbDays,(parseInt(priceInfo.TotalFinalPrice*rate,10)/100).toFixed(2),(parseInt(priceInfo.TotalFinalPrice*rate/nbDays,10)/100).toFixed(2),(parseInt(priceInfo.TotalFinalFee*rate,10)/100).toFixed(2),(parseInt((priceInfo.TotalFinalPrice-priceInfo.TotalFinalFee)*rate,10)/100).toFixed(2));}
this.priceContainer.append(html);this.priceContainer.css("height","auto");$j(".currency-symbol",this.priceContainer).text(this.currentCurrency.Symbol);},show:function()
{this.wrapper.slideDown();},hide:function()
{this.wrapper.slideUp();}},allCurrency:{},currentCurrency:null,wrapper:null,calendarFrom:null,calendarTo:null,flat:null,init:function(id,cityName,defaultCurrency,flat,calendarViewUrl,htmlTemplateWithoutDiscount,htmlTemplateWithDiscount)
{var self=this;this.flat=flat;this.wrapper=$j('#'+id).css({position:"relative"});this.priceDetails.init($j('.price-details',this.wrapper),defaultCurrency,this,htmlTemplateWithDiscount,htmlTemplateWithoutDiscount);this.calendarFrom=$j($j('.CukeCalendarBeApartSearch')[0]).CukeCalendar();this.calendarTo=$j($j('.CukeCalendarBeApartSearch')[1]).CukeCalendar();this.calendarFrom.select(function(){self.priceDetails.hide();});this.calendarTo.select(function(){self.priceDetails.hide();});$j('.pers-selector',this.wrapper).change(function(){self.priceDetails.hide();});$j('.calendar',this.wrapper).click(function()
{Cuke.Modal.enter(Cuke.AbsoluteHost+calendarViewUrl+"ID="+self.flat.FlatID+"&CukeNoEdit=2",{size:[500,275]});});$j('.check-button',this.wrapper).click(function()
{var nbPers=parseInt($j('.pers-selector',self.wrapper).val(),10);if(nbPers>0)
{loader.addTo(self.wrapper);$j.ajax({type:"POST",contentType:"application/json; charset=utf-8",url:Cuke.RootUrl+"BeApart/Basic/Service/SearchService.asmx/PutInSession",data:JSON.stringify({searchInfo:{From:self.calendarFrom.selected[0],To:self.calendarTo.selected[0],NbPers:nbPers,City:cityName}}),dataType:"json",success:function(resp)
{if(resp.d.Result===0)
{self.isAvailable(function(data)
{loader.remove();var unavailable=$j('.date-unavailable',self.wrapper).hide();if(data.Xml!==null)
{self.priceDetails.hide();var xmlDoc=stringToXmlDocument(data.Xml);var errorMessages=[];var minStayNode=xmlDoc.getElementsByTagName("MinStay")[0];if(minStayNode)
{var minStay=0;for(var i=0;i<minStayNode.childNodes.length;++i)
{var value=parseInt(minStayNode.childNodes[i].getAttribute("value"),10);if(value>minStay){minStay=value;}}
errorMessages.push(Cuke.format("{0}: {1} {2}",Cuke.getString("BeApart.Flat.MinStay"),minStay,minStay>1?Cuke.getString("BeApart.Nights"):Cuke.getString("BeApart.Night")));}
var maxPersNode=xmlDoc.getElementsByTagName("MaxPers")[0];if(maxPersNode)
{var persValue=maxPersNode.getAttribute("value");errorMessages.push(Cuke.format(Cuke.getString("BeApart.Flat.ErrorSelectPersonn"),persValue+" "+(parseInt(persValue,10)>1?Cuke.getString("BeApart.Personns"):Cuke.getString("BeApart.Personn"))));}
var unbreakableNode=xmlDoc.getElementsByTagName("UnbreakableRange")[0];if(unbreakableNode&&unbreakableNode.hasChildNodes())
{var dayNode=unbreakableNode.childNodes[0];errorMessages.push(Cuke.format(Cuke.getString("BeApart.Flat.ErrorUnbreakableRange"),timeStampToDate(dayNode.getAttribute("begin")).format("dd/mm/yyyy"),timeStampToDate(dayNode.getAttribute("end")).format("dd/mm/yyyy")));}
if(errorMessages.length>0)
{var html="";for(var idx=0;idx<errorMessages.length;++idx)
{if(html.length>0){html+="<br/>";}
html+=errorMessages[idx];}
Cuke.Window.alert(Cuke.format(Cuke.getString("BeApart.BookingCalculatorErrorMessage"),html),null,{size:[350,200]});}
else{unavailable.show();}}
else
{self.flat=data.Flat;self.priceDetails.update();self.priceDetails.show();}});}
else{alert(resp.d.ErrorText);}}});}
else{Cuke.Window.alert(Cuke.getString("BeApart.SearchSelectPersonn"),null,{size:[350,100]});}
return false;});},isAvailable:function(callBack)
{var self=this;$j.ajax({type:"POST",contentType:"application/json; charset=utf-8",url:Cuke.rootUrl+"BeApart/Basic/Service/FlatToRentService.asmx/IsAvailable",data:JSON.stringify({flatId:self.flat.FlatID,from:self.calendarFrom.selected[0],to:self.calendarTo.selected[0],nbPers:$j('.pers-selector',self.wrapper).val()}),dataType:"json",success:function(resp)
{if(resp.d.Result===0)
{callBack(resp.d.Data);}
else{alert(resp.d.ErrorText);}}});}});})();
