var prevetivoVersion = "preventivo2evo.js.php";var checkoutFormVersion = "form3evo.php";var myIPaddress = "62.210.77.51"
var onlyBE = ""
var SelectedDatesGreen = {};

var SelectedDatesOrange = {};

var SelectedDatesRed = {};

var SeletedText = {};

var clientActive = "0";var error = "Error";var clientId, linkerParam;
var currentDomain = document.location.host.replace("www.", ""); 

(function(i,s,o,g,r,a,m){
	i['GoogleAnalyticsObject']=r;
	i[r]=i[r]||function(){
		(i[r].q=i[r].q||[]).push(arguments)
	},i[r].l=1*new Date();
	
	a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];
	a.async=1;
	a.src=g;
	m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga(function(){
	ga('create', gaCode, 'auto', { 'allowLinker' : true }, true);
	ga('set', 'forceSSL', true);
	ga('send', 'pageview');
	ga('require', 'linker');
	ga('linker:autoLink', [currentDomain, /^bbliverate\.(com)$/, /^octorate\.(com)$/], true);

	ga(function(tracker){
		clientId = tracker.get('clientId');
		linkerParam = tracker.get('linkerParam');
	});
	
	window.onload = function(){		
		var linker;
		
		var bookElement = document.getElementById("book");
		
		if(typeof bookElement !== 'undefined' && bookElement !== null && bookElement.length > 0){
		// if(document.getElementById('book')){
			var setBook = document.getElementById('book');
			
			addListener(setBook, 'mousedown', decorateMe);
			addListener(setBook, 'keydown', decorateMe);
		}
		
		var resubmitElement = document.getElementById("resasubmit");
		
		if(typeof resubmitElement !== 'undefined' && resubmitElement !== null && resubmitElement.length > 0){
		// if(document.getElementById('resasubmit').length > 0){
			var setSubmit = document.getElementById('resasubmit');
			
			addListener(setSubmit, 'mousedown', decorateMe);
			addListener(setSubmit, 'keydown', decorateMe);
		}
		
		var fomCount = document.getElementsByClassName("bookform");
		
		if(typeof fomCount !== 'undefined' && fomCount !== null && fomCount.length > 0){			
		// if(fomCount > 0){
			for(count = 0; count < fomCount; count++) {
				var setForms = document.getElementsByClassName("demo")[count];
				
				addListener(setForms, 'submit', decorateForm);
			}
		}
		
		var dformElement = document.getElementById("dati-form");
		
		if(typeof dformElement !== 'undefined' && dformElement !== null && dformElement.length > 0){
		// if(document.getElementById('dati-form').length > 0){
			var setBooking = document.getElementById('dati-form');
			
			addListener(setBooking, 'submit', decorateForm);
		}

		var btnbankElement = document.getElementById("btnbank");
		
		if(typeof btnbankElement !== 'undefined' && btnbankElement !== null && btnbankElement.length > 0){
		// if(document.getElementById('btnbank').length > 0){
			var setBank = document.getElementById('dati-form');
			
			addListener(setBank, 'submit', decorateForm);
		}
		
		var rsubmt1Element = document.getElementById("resasubmit1");
		
		if(typeof rsubmt1Element !== 'undefined' && rsubmt1Element !== null && rsubmt1Element.length > 0){		
		// if(document.getElementById('resasubmit1').length > 0){
			var setPay = document.getElementById('dati-form');
			
			addListener(setPay, 'submit', decorateForm);
		}
		
		var rsubmt2Element = document.getElementById("resasubmit2");
		
		if(typeof rsubmt2Element !== 'undefined' && rsubmt2Element !== null && rsubmt2Element.length > 0){
		// if(document.getElementById('resasubmit2').length > 0){
			var setPayment = document.getElementById('dati-form');
			
			addListener(setPayment, 'submit', decorateForm);
		}
		
		function decorateMe(event){
			event = event || window.event;
					
			var target = event.target || event.srcElement;
					
			if(target && target.href){
				ga('linker:decorate', target);
			}
		}
		
		function decorateForm(event){
			event = event || window.event;
			
			var target = event.target || event.srcElement;
			
			if(target && target.action){
				ga('linker:decorate', target);
			}
		}
		
		function addListener(element, type, callback){
			if(element.addEventListener){
				element.addEventListener(type, callback);
			} else if(element.attachEvent){
				element.attachEvent('on' + type, callback);
			}
		}
	};
});

function pushWidgetGA(getAction, getLabel, getValue){
	if(typeof getValue != 'undefined'){
		ga('send', 'event', 'OctoRate - Widget', getAction, getLabel, parseInt(getValue));
	} else {
		ga('send', 'event', 'OctoRate - Widget', getAction, getLabel);
	}
}

function pushPreventivoGA(getAction, getLabel, getValue){
	if(typeof getValue != 'undefined'){				
		ga('send', 'event', 'OctoRate - Rooms', getAction, getLabel, parseInt(getValue));
	} else {
		ga('send', 'event', 'OctoRate - Rooms', getAction, getLabel);
	}
}

function pushReservationGA(getAction, getLabel, getValue){
	if(typeof getValue != 'undefined'){				
		ga('send', 'event', 'OctoRate - Reservation', getAction, getLabel, parseInt(getValue));
	} else {
		ga('send', 'event', 'OctoRate - Reservation', getAction, getLabel);
	}
}

function pushResultsGA(getAction, getLabel, getValue){
	if(typeof getValue != 'undefined'){				
		ga('send', 'event', 'OctoRate - Results', getAction, getLabel, parseInt(getValue));
	} else {
		ga('send', 'event', 'OctoRate - Results', getAction, getLabel);
	}
}

function pushBookGA(getAction, getLabel, getValue){
	if(typeof getValue != 'undefined'){				
		ga('send', 'event', 'OctoRate - Booking', getAction, getLabel, parseInt(getValue));
	} else {
		ga('send', 'event', 'OctoRate - Booking', getAction, getLabel);
	}
}

function pushConfirmationGA(getAction, getLabel, getValue){
	if(typeof getValue != 'undefined'){				
		ga('send', 'event', 'OctoRate - Confirmation', getAction, getLabel, parseInt(getValue));
	} else {
		ga('send', 'event', 'OctoRate - Confirmation', getAction, getLabel);
	}
}
var octohost = window.location.protocol+'//www.octorate.com/';
var host = octohost;

function addCss(styles,targetDocument){
	var add = function(path){
		//alert(path); 
		var link = document.createElement('link');
		
		if(path.indexOf('http') == 0){
			link.setAttribute('href', path);
		}else{
			link.setAttribute('href', octohost+path);
		}
		
		link.setAttribute('rel' ,'stylesheet');
		link.setAttribute('type','text/css');
		
		if(targetDocument){
			if(myIPaddress  == '87.97.186.208' || myIPaddress == '2.239.87.177x'){
				targetDocument.getElementsByTagName('body')[0].appendChild(link);
			} else {
				targetDocument.getElementsByTagName('head')[0].appendChild(link);
			}
		}else{
			if(myIPaddress  == '87.97.186.208' || myIPaddress == '2.239.87.177x'){
				document.getElementsByTagName('body')[0].appendChild(link);
			} else {
				document.getElementsByTagName('head')[0].appendChild(link);
			}
		}
    }
    
	if(typeof styles == 'string'){
	    add(styles);
	}else{
    	for(var style in styles){
        	if(typeof styles[style] == 'string'){
            	add(styles[style]);
	        }
    	}
    }
};

function addJs(path,callback,id,documentContext){
    if(!documentContext){
        documentContext = document;
    }
	
    var scriptElem = documentContext.createElement('script');
    scriptElem.setAttribute('src' ,octohost+path);
    // alert(octohost+path);
	if(id){
        scriptElem.setAttribute('id' ,id);
    }
    
	scriptElem.setAttribute('type','text/javascript');
    
	if(typeof callback == 'function'){
        if(scriptElem.addEventListener){
            scriptElem.addEventListener('load', callback, false)
		}else{
            scriptElem.onreadystatechange = callback;
        }
    }

	documentContext.getElementsByTagName('body')[0].appendChild(scriptElem);
};
function SwitchHelper(defaultContainer,links,jQuery){
	this.$ = jQuery;
	this.containerSelector = defaultContainer;
	this.links = links;
	this.initEvents();
}

SwitchHelper.prototype.initEvents = function(){
	var $=this.$;
	var self=this;
	
	$.each(this.links,function(){
		var linkObj=this;
		
		$(linkObj.linkSelector).click(function(){
			if(linkObj.linkSelector==self.container){
				return;
			}
			
			$(self.containerSelector).fadeOut(250,function(){
				$(linkObj.containerSelector).fadeIn(250,function(){
					self.containerSelector=linkObj.containerSelector;
				});
			});
		});
	});
}

SwitchHelper.prototype.initHotelInfo = function(){
	var $=this.$;
	var clicked;
	
	$('#myframe .hotelInfoBtn').toggle(function(){
		$(this).next('.hotel-data').slideDown();
		$(this).removeClass('bbUpArrow').addClass('bbDownArrow');
	}, function(){
		$(this).next('.hotel-data').slideUp();
		$(this).removeClass('bbDownArrow').addClass('bbUpArrow');
	});
	
	$('#myframe .showDescription').click(function(){
		clicked=$(this);
		clicked.nextAll('.showed').fadeOut(250,function(){
			clicked.nextAll('.description').css('display','block').addClass('showed');
		});
	});
	
	$('#myframe .showPhotos').click(function(){
		clicked=$(this);
		clicked.nextAll('.showed').fadeOut(250,function(){
			$(this).removeClass('showed');
			clicked.nextAll('.photos').css('display','block').addClass('showed');
		});
	});
	
	$('#myframe .showMap').click(function(){
		clicked=$(this);
		clicked.nextAll('.showed').fadeOut(250,function(){
			clicked.nextAll('.map').css('display','block').addClass('showed');
		});
	});
	
	$('#myframe .showComments').click(function(){
        clicked=$(this);
        clicked.nextAll('.showed').fadeOut(250,function(){
            clicked.nextAll('.comments').css('display','block').addClass('showed');
		});
	});
};
function init_all_tooltips(jQueryObj,tooltips,popup){
	if(tooltips){
		for(var key in tooltips){
			initTooltip(jQueryObj,tooltips[key],popup);
		}
	}
}

function init_extras_tooltips(jQueryObj,popup){
	var $ = jQueryObj;

	$('#dati-form .extras .extras-tooltip-switcher').each(function(){
		initTooltip(jQueryObj,{
			switcher: this,
			tooltip: $(this).next()
		},popup);
	});
}

function initTooltip(jQueryObj,tooltipObj,popup){
    var config = { tip: tooltipObj.tooltip, position: "top center" };
	
    if(!popup){
        config.onShow = onShow;
    }
	
	jQueryObj(tooltipObj.switcher).tooltip(config);
}

function onShow(e){
    var tooltip = e.target.getTip();
    var trigger = e.target.getTrigger();

	tooltip.css('position','fixed');
	
    var top = trigger.position().top - tooltip.height() - trigger.height();

	tooltip.css('top',top);
}
RoomsCountControl = {
    rooms: {},
    refreshOptions: function (room_ids) {
        var self = this;
        var select;
        var counter;
        var maxOptions;
        var sameOtherRooms;

        self.$.each(room_ids, function (key, room_id) {
            select = self.$('.room_' + room_id + ' select.rooms-count');
            counter = 1;
            sameOtherRooms = 0;

            self.$.each(self.sameRooms[room_id], function (key, item) {
                if (item != room_id) {
                    var s = self.$('.room_' + item + ' select.rooms-count');
                    var v = s.val();
                    if (v > 0) {
                        sameOtherRooms += parseInt(v);
                    }
                }
            });

            if (typeof self.rooms[room_id] != 'undefined') {
                maxOptions = self.rooms[room_id].maxAvailability - sameOtherRooms;

                select.children('option').each(function () {
                    if (self.$(this).val() == 0) {
                        return;
                    }

                    if (counter > maxOptions) {
                        self.$(this).attr('disabled', 'true');
                        self.$(this).css('display', 'none');
                    } else {
                        self.$(this).removeAttr('disabled');
                        self.$(this).css('display', 'block');
                    }

                    counter++;
                });
            }
        });
    },
    init: function ($) {
        var self = this;
        self.$ = $;
        self.sameRooms = BBliverate.sameRooms || {};

        $('select.rooms-count').each(function (key, item) {
//            var _class = $(this).parent().parent().attr('class');
//            var room_id = parseInt(_class.match(/room_([0-9]+)/)[1]);
            var room_id = Controls.getRoomId(this);
            if (typeof self.rooms[room_id] == 'undefined') {
                self.rooms[room_id] = {maxAvailability: $(item).children('option').length - 1};
            }
        });
    }
};

var Controls = {
    $: {},
    init: function ($) {
        this.$ = $;

        try {
            RoomsCountControl.init($);
        } catch (e) {
        }

        $('select.rooms-count').change(function () {
//            var _class = $(this).parent().parent().attr('class');
//            var room_id = _class.match(/room_([0-9]+)/)[1];
            var room_id = Controls.getRoomId(this);

            if (typeof RoomsCountControl.sameRooms[room_id] != 'undefined' && RoomsCountControl.sameRooms[room_id] != null) {
                RoomsCountControl.refreshOptions(RoomsCountControl.sameRooms[room_id]);
            }
        });
    },
    getRoomId: function (s) {
        return $(s).parent().find('input.room_id_new').val();
    }
};
var Cookie = {
    setCookie: function (name, value, options) {
        options = options || {};

        var expires = '';
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        var date;

        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }

        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }, getCookie: function (name) {
        var cookieValue = null;
        var cookies;
        var cookie;

        if (document.cookie && document.cookie != '') {
            cookies = document.cookie.split(';');

            for (var i = 0; i < cookies.length; i++) {
                cookie = cookies[i].replace(' ', '');

                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }

        return cookieValue;
    }
};

function EngineLightbox() {
    this.$ = {};
    this.onCreate = false;
    this.onRemove = false;
    this.isCreated = false;
    this.create = function (content, $) {
        this.$ = $;
        this.refresh();

        $('body').append(content);
        // $('#light_2').css('top',$(window).scrollTop()+10);
        $('#fade_2').css('height', $(document).height() + 'px');

        $(window).scroll(function (event) {
            $('#light_2').css('top', $(window).scrollTop() + 10)
        });

        (function (self) {
            $('#click_close').add('#fade_2').click(function () {
                $('#light_2,#fade_2').fadeOut(500, function () {
                    self.remove();
                });

                return false;
            })
        })(this);

        $('#fade_2').fadeTo(500, 0.80, function () {
            $('#light_2').css('display', 'block');
        });

        if (typeof this.onCreate == 'function') {
            this.onCreate();
        }

        this.created(true);
    };

    this.refresh = function () {
        if (!this.created()) {
            return;
        }

        this.removeHtml();
    };

    this.removeHtml = function () {
        var $ = this.$;

        try {
            $('#light_2').remove();
            $('#fade_2').remove()
        } catch (e) {
        }
    };

    this.remove = function () {
        this.removeHtml();

        if (typeof this.onRemove == 'function') {
            this.onRemove()
        }

        this.created(false)
    };

    this.created = function (created) {
        if (typeof created != 'undefined') {
            this.isCreated = created
        }

        return this.isCreated
    };

    this.addEventListiner = function (type, callback) {
        if (typeof callback != 'function') {
            return false
        }

        switch (type) {
            case'onCreate':
                this.onCreate = callback;
                break;
            case'onRemove':
                this.onRemove = callback;
                break;
            default:
                alert('wrong type')
        }
    }
}
;

var Widget = {
    $: {},
    lightBox: {},
    first: true,
    timerId: null,
    chatUniqe: '',
    paused: false,
    typing: 0,
    prevCache: '',
    connectOpen: false,
    youPrefix: 'You',
    chatName: 'Admin',
    sendForm: function (form, file) {
        var data = this.$(form).serialize();
        var contotote = this.$('input[name=contotote]').val();

        // GoogleAnalitycs.pushReservation('Reservation submitted', 'contotote '+contotote,contotote);
        pushReservationGA('Reservation submitted', 'contotote ' + contotote, contotote);

        addJs('secure/' + file + '?callback=echoForm&' + data)
    }, submitCoupon: function () {
        var $ = this.$;
        var coupon = $('input[name=couponCode]');

        addJs('secure/' + checkoutFormVersion + '?callback=handleCoupon&couponCode=' + coupon.val() + '&siteKey=' + siteKey)
    }, handleCoupon: function (respond) {
        CouponsControl.applyCouponCode(this.$, respond)
    }, echoForm: function (content) {
        this.hideAjaxLoader();

        var self = this;
        var $ = self.$;

        addJs("js/jquery.tools.min.js", function () {
            var tooltips = [
                {switcher: '#dati-form p.room-type', tooltip: '#dati-form div.room-description'},
                {switcher: 'img.cancpol-tooltip-switcher', tooltip: '#cancpol-tooltip'}
            ];

            init_all_tooltips(self.$, tooltips)
            init_extras_tooltips(self.$);
        });

        self.$('#myframe').removeClass('room-step');
        self.$('#myframe').addClass('form-step');
        self.$('#myframe').html(content);

        $('input[name=bon]').click(function () {
            if ($(this).attr('checked')) {
                $('.hiddable').fadeOut();
                $(this).parent().parent().next().css('display', 'table-row')
            } else {
                $('.hiddable').fadeIn();
                $(this).parent().parent().next().css('display', 'none')
            }
        })

        CouponsControl.initWidgetCoupons(this.$)
    }, echoContent: function (content) {
        this.hideAjaxLoader();

        if (content == 'corruptedNumber') {
            alert('Incorrect number, please contact with site administrator')
        } else {
            if (!(this.lightBox instanceof EngineLightbox)) {
                this.lightBox = new EngineLightbox()
            }

            this.$('#myframe').removeClass('form-step');
            this.$('#myframe').addClass('room-step');
            this.lightBox.create(content, newJquery)
        }
    }, echoBooking: function (content) {
        this.hideAjaxLoader();

        if (!(this.lightBox instanceof EngineLightbox)) {
            this.lightBox = new EngineLightbox();

            (function (_widget) {
                _widget.lightBox.addEventListiner('onRemove', function () {
                    _widget.connectOpen = false;
                    _widget.releasePause()
                })
            })(this)
        }

        this.lightBox.create(content, newJquery)
    }, releasePause: function () {
        if (this.paused) {
            var $ = this.$;
            var path = octohost + 'hotel/admin/hot_chat/messager.js.php?func=waitNewAction&chatPause=0&chatUniqe=' + this.chatUniqe + '&typing=' + this.typing;
            path += '&callback=?';
            $.getJSON(path, function (data) {});

            this.connectOpen = true;
            this.paused = false
        }
    }, sendMsg: function (msg) {
        if (msg) {
            var respond = document.getElementById('chat-messages');

            if (this.first) {
                this.$('#chat-container .welcome-msg').text('Please wait for operator respond');
                this.first = false
            }

            respond.innerHTML += '<p class="client">' + this.youPrefix + ': ' + msg + '</p>';
            addJs('hotel/admin/hot_chat/messager.js.php?msg=' + encodeURIComponent(msg) + '&chatUniqe=' + this.chatUniqe);

            this.releasePause()
        }
    }, closeChat: function (data) {
        this.connectOpen = false;
        clearInterval(this.timerId);
        this.$('#chat-container .chat').html(data.text)
    }, scrollToBottom: function (item) {
        var $ = this.$;
        item.scrollTop($('#chat-messages').height())
    }, waitNewMessages: function (data) {
        var $ = this.$;
        if (!this.chatUniqe) {
            return
        }
        clearTimeout(this.timerId);
        if ((this.connectOpen == false || data.wait == true) && (typeof this.chatUniqe == 'string')) {
            this.connectOpen = true;
            var path = octohost + 'hotel/admin/hot_chat/messager.js.php?func=waitNewAction&chatUniqe=' + this.chatUniqe + '&typing=' + this.typing;
            path += '&jsoncallback=?';
            try {
                $('#waitScript').remove()
            } catch (e) {
            }
            this.timerId = setTimeout(function () {
                $.getJSON(path, function (respondData) {})
            }, data.timer)
        }
    }, doNothing: function (data) {
        this.connectOpen = false;
        this.waitNewMessages({'timer': 100});
    }, adminTyping: function (data) {
        var $ = this.$;
        this.typing = data.typing.curent;

        $('#chat-container .welcome-msg').text(data.typing.message);

        this.connectOpen = false;
        this.waitNewMessages({'timer': 100});
    }, passNext: function () {
        this.connectOpen = false;
        this.paused = true;
    },
    reciveMsg: function (data) {
        var $ = this.$;
        if (data.respond) {
            this.typing = 1;
            $('#chat-container .welcome-msg').text('');
            var respond = document.getElementById('chat-messages');
            respond.innerHTML += '<p class="admin">' + this.chatName + ': ' + data.respond + '</p>';
            this.scrollToBottom($('#chat-respond'));
            delete data;
            this.connectOpen = false;
            this.waitNewMessages({
                'timer': 100
            })
        }
    },
    checkForRespond: function () {
        var $ = this.$;
        var string = window.location.search;
        var num;
        var num2;
        if (string != '') {
            try {
                num = string.match(/(?:kznum=)(\S+$)/i)[1]
            } catch (e) {
            }
            try {
                num2 = string.match(/(?:kznum2=)(\S+$)/i)[1]
            } catch (e) {
            }
        }
        if (num2) {
            addJs('secure/okon_1p.php?callback=echoContent&num2=' + num2)
        } else if (num) {
            addJs('secure/' + checkoutFormVersion + '?callback=echoContent&pag=KO&num=' + num)
        } else {
            marketingTool.detectMobile();
        }
    },
    setChatPosition: function (position, first, $) {
        if (first) {
            $('#chat-container').css({
                position: 'absolute',
                right: position.right,
                bottom: position.bottom,
                left: position.left,
                top: position.top
            })
        } else {
            if (position.top_position) {
                $('#chat-container').animate({
                    top: position.top
                }, {
                    duration: 300,
                    queue: false
                })
            } else if (position.bottom_position) {
                $('#chat-container').animate({
                    bottom: position.bottom
                }, {
                    duration: 300,
                    queue: false
                })
            }
        }
    },
    setEmbed: function (params, data, $) {
        var embed = {};
        var selector = params.embedSelector;
        embed.length = 0;
        if (selector != '') {
            embed = $(selector)
        }
        var widget = this;
        if (embed.length == 1) {
            embed.append(data)
        } else {
            $('body').append(data);
            var position = {};
            if (!$('#chat-container').hasClass('bbhorizontal')) {
                var middle = $(window).width() / 2 - 125;
            } else {
                var middle = 0;
            }
            switch (parseInt(params.pos_hor_widjet)) {
                case 1:
                    position = {
                        top: '0px',
                        left: '0px',
                        right: 'auto',
                        bottom: 'auto',
                        top_position: true
                    }
                    break;
                case 2:
                    position = {
                        top: '0px',
                        left: 'auto',
                        right: '0px',
                        bottom: 'auto',
                        top_position: true
                    }
                    break;
                case 3:
                    position = {
                        top: 'auto',
                        left: '0px',
                        right: 'auto',
                        bottom: '0px',
                        bottom_position: true
                    }
                    break;
                case 5:
                    position = {
                        top: '0px',
                        left: middle,
                        right: 'auto',
                        bottom: 'auto',
                        top_position: true
                    }
                    break;
                case 6:
                    position = {
                        top: 'auto',
                        left: middle,
                        right: 'auto',
                        bottom: '0px',
                        bottom_position: true
                    }
                    break;
                case 4:
                default:
                    position = {
                        top: 'auto',
                        left: 'auto',
                        right: '0px',
                        bottom: '0px',
                        bottom_position: true
                    }
                    break;
            }
            if (position.top_position) {
                position.top = $(window).scrollTop();
            } else if (position.bottom_position) {
                position.bottom = 0 - $(window).scrollTop();
            }
            widget.setChatPosition(position, true, $);
            $(window).scroll(function () {
                if (position.top_position) {
                    position.top = $(window).scrollTop();
                } else if (position.bottom_position) {
                    position.bottom = 0 - $(window).scrollTop();
                }
                widget.setChatPosition(position, false, $)
            })
        }
    },
    bookForm: function ($, date1, date2) {
        var button_was_clicked = false;

        if (typeof $ != 'function') {
            $ = this.$
        }

        var bookingButton = $('.img-booking');
        bookingButton.removeAttr('disabled');

        this.toggleContacUsInit(date1, date2);
        Controls.init($);

        if (bookingButton.length == 0) {
            return
        }

        bookingButton.click(function () {
            if (button_was_clicked) {
                bookingButton.attr('disabled', 'true')
                return;
            }

            button_was_clicked = true;

            var data = '';
            var contotote = 0;
            var form = $(this).parents('form');

            form.find('input,select').each(function () {
                var item = $(this);
                var name = item.attr('name');
                var value = item.val();

                if (item.attr('type') != 'checkbox') {
                    if (name.indexOf('contotote') > -1) {
                        var selectValue = item.prevAll('.rooms-count').val();

                        if (selectValue > 0) {
                            contotote += parseInt(value) * selectValue;
                        }
                    }

                    data += name + '=' + value + '&';
                } else if (item.attr('type') == 'checkbox' && item.attr('checked') == true) {
                    data += name + '=' + value + '&';
                }
            });

            if (contotote > 0) {
                if (typeof console != 'undefined') {
                }

                // GoogleAnalitycs.pushPreventivo('Book clicked', 'contotote '+contotote,contotote);
                // pushPreventivoGA('Book clicked', 'contotote '+contotote, contotote);
                addJs('secure/' + checkoutFormVersion + '?' + data + 'callback=echoForm');

                if (typeof toggle_loader != 'undefined') {
                    toggle_loader(this);
                }
            } else {
                button_was_clicked = false;
                bookingButton.removeAttr('disabled')
                alert('Please select at least one room');
            }
        })
    },
    toggleContacUsInit: function (date1, date2) {
        var $ = this.$;
        var switchHelper = new SwitchHelper('#myframe .frameContent', [{
                linkSelector: '#myframe span.contact-us',
                containerSelector: '#myframe div.contact-us'
            }, {
                linkSelector: '#myframe #back_contact_us',
                containerSelector: '#myframe .frameContent'
            }], $);
        switchHelper.initHotelInfo();
        $('#submit_contact_us').click(function () {
            var email = $('#myframe .contact-us input[name=email]').val();
            var message = encodeURI($('#myframe .contact-us textarea[name=message]').val());
            if (email.length > 0) {
                addJs('hotel/admin/hot_php/contactUs.php?cid=' + siteKey + '&email=' + email + '&from=' + date1 + '&to=' + date2 + '&message=' + message)
            } else {
                $('#myframe .frameContent').prepend('<span class=""error>You should enter correct email</span>')
            }
        })
    },
    contactUsRespond: function (respond) {
        var $ = this.$;
        $('#myframe .frameContent').fadeIn(250, function () {
            $('#myframe div.contact-us').html('<h3 style="text-align:center;color:#4C4646;font-family:Tahoma;">' + respond + '</h2>');
            $('#myframe span.contact-us').remove()
        })
    },
    moveBack: function () {
        this.$('#myframe').html(this.prevCache);
        this.$('#myframe').removeClass('form-step');
        this.$('#myframe').addClass('room-step');
        this.bookForm()
    },
    flashEmbedFix: function () {
        var embeds = document.getElementsByTagName('embed');
        var objects = document.getElementsByTagName('object');
        var param = document.createElement('param');
        var save = {};

        var parent = {};

        var key = 0;
        param.setAttribute('name', 'wmode');
        param.setAttribute('value', 'transparent');
        if (objects.length > 0) {
            for (key in objects) {
                if (!isNaN(parseInt(key)) && typeof objects[key] != 'undefined') {
                    save = objects[key].cloneNode(true);
                    parent = objects[key].parentNode;
                    parent.removeChild(objects[key]);
                    save.insertBefore(param, save.firstChild);
                    parent.appendChild(save)
                }
            }
        }
        if (embeds.length > 0) {
            for (key in embeds) {
                if (!isNaN(parseInt(key)) && typeof embeds[key] != 'undefined') {
                    save = embeds[key].cloneNode(true);
                    parent = embeds[key].parentNode;
                    parent.removeChild(embeds[key]);
                    save.setAttribute('wmode', 'transparent');
                    parent.appendChild(save)
                }
            }
        }
    }, bookClick: function (langId) {
        var $ = this.$;
        var _widget = this;
        var date1 = this.date1 = $('#from').val();
        var date2 = this.date2 = $('#to').val();
        var pax = this.pax = $('#pax').val();
        var date1Array = date1.split('/');
        var date2Array = date2.split('/');
        var fromDay = parseInt(date1Array[0].replace(/^0/, ''));
        var toDay = parseInt(date2Array[0].replace(/^0/, ''));
        var fromMonth = parseInt(date1Array[1].replace(/^0/, '')) - 1;
        var toMonth = parseInt(date2Array[1].replace(/^0/, '')) - 1;
        var date1obj = new Date(date1Array[2], fromMonth, fromDay);
        var date2obj = new Date(date2Array[2], toMonth, toDay);
        var lingua;

        if (date2obj.getTime() > date1obj.getTime()) {
            // GoogleAnalitycs.pushWidget('click book', 'from date: '+date1+' to date: '+date2);
            pushWidgetGA('click book', 'from date: ' + date1 + ' to date: ' + date2);

            var siteKey = $('#siteKey').val();

            var mobile = marketingTool.mobileAndTabletcheck();
            if (mobile) {
                window.location = 'https://www.octorate.com/mobilePages/en/Reservation/1/?onlybe=&siteKey=' + siteKey + '&from=' + date1 + '&to=' + date2;
            } else {
                //if(typeof isPopup!='undefined' || typeof widgetRedirect != 'undefined'){
                var path = prevetivoVersion;
                //} else {
                //var path = 'preventivo2.js.php';
                //}
                path += '?callback=echoBooking&pax=' + pax + '&siteKey=' + siteKey + '&date1=' + date1 + '&date2=' + date2 + '&onlybe=' + onlyBE;

                if (typeof this.chatUniqe != 'undefined' && typeof isPopup == 'undefined') {
                    path += '&chatUniqe=' + this.chatUniqe;
                }

                if (typeof langId != 'undefined') {
                    path += '&bbliverate_lingua=' + langId
                } else if (typeof language != 'undefined') {
                    path += '&bbliverate_lingua=' + language;
                }

                if (!this.paused && typeof this.chatUniqe == 'string' && typeof isPopup == 'undefined') {
                    addJs('hotel/admin/hot_chat/messager.js.php?chatPause=1&chatUniqe=' + this.chatUniqe)
                }

                if (typeof isPopup != 'undefined') {
                    path += '&isPopup=1';
                    _widget.openPopup('https://www.octorate.com/' + path + '&' + linkerParam);
                    // _widget.openPopup(octohost+path);
                } else if (typeof widgetRedirect != 'undefined') {
                    path += '&isDirect=1';
                    path += '&back_site_url=' + encodeURIComponent(window.location.href);

                    window.location.href = 'https://www.octorate.com/' + path + '&' + linkerParam;
                    // window.location.href = octohost+path;
                } else {
                    _widget.showAjaxLoader();

                    addJs(path, function () {
                        _widget.bookForm(null, date1, date2);
                        _widget.prevCache = $('#myframe').html()
                    });

                    this.prevCache = _widget.prevCache;
                }
            }
        } else {
            alert('Incorrect date: From date bigger than To date');
        }

        return false;
    }, fullScreen: function (langId) {
        var $ = this.$;
        var _widget = this;
        var siteKey = $('#siteKey').val();

        _widget.showAjaxLoader();

        addJs('fullmapscreen.php?callback=echoBooking&siteKey=' + siteKey, function () {
            _widget.bookForm(null, date1, date2);
            _widget.prevCache = $('#myframe').html();
        });

        this.prevCache = _widget.prevCache;
    }, openPopup: function (path) {
        var coordX, coordY, width = 750, height = 400;
        var $ = this.$;

        coordX = $(window).width() / 2 - width / 2;
        coordY = $(window).height() * (0.2);

        if (typeof this.prevWindow != 'undefined') {
            this.prevWindow.close()
        }

        this.prevWindow = window.open(path, 'bookwidget', 'width=' + width + ',height=' + height + ',left=' + coordX + ',top=' + coordY + ',resizable=1,scrollbars=1')
    }, showAjaxLoader: function () {
        var $ = this.$;
        var top = $(window).height() / 2;
        var left = $(window).width() / 2 - 110;

        if ($('#chat-container #from').val() != '' && $('#chat-container #to').val() != '') {
            this.$('body').append('<div id="bbliverate-ajax_loader" style="position:fixed; top:' + top + 'px; left: ' + left + 'px;"><img src="' + octohost + '/immagini/widget-ajax-loader.gif"></div>')
        }
    }, hideAjaxLoader: function () {
        this.$('#bbliverate-ajax_loader').remove();
    }, init: function (myjQuery) {
        this.flashEmbedFix();
        this.$ = myjQuery;

        var $ = myjQuery;

        try {
            this.chatUniqe = $('#chatUniqe').val()
        } catch (e) {
        }

        var _widget = this;
        var date = new Date();
        var href = window.location.href;

        href = href.replace('/', '%2F', 'g');

        if (typeof _widget.chatUniqe == 'string') {
            addJs('hotel/admin/hot_chat/messager.js.php?callback=setHistory&href=' + href + '&chatUniqe=' + _widget.chatUniqe + '&time=' + date.getTime())
        }

        this.checkForRespond();

        try {
            $('#icaluWidgetSwitcher').toggle(function () {
                if ($("#showfromside").val() == 'right') {
                    $(this).parent().animate({right: '-12px'}, 750);
                } else {
                    $(this).parent().animate({left: '-8px'}, 750);
                }
            }, function () {
                if ($("#showfromside").val() == 'right') {
                    $(this).parent().animate({right: '-619px'}, 750)
                } else {
                    $(this).parent().animate({left: '-617px'}, 750)
                }
            })
        } catch (e) {
        }

        try {
            $('#send').click(function () {
                _widget.sendMsg($('#chat-container .message').val(), this.chatUniqe);
                $('#chat-container .message').val('');
                _widget.scrollToBottom($('#chat-respond'));
                return false
            });

            if (defaultVisible == 1) {
                $('form[name=chat]').css('display', 'none');
                $('#chat-container .close').html('<img src="https://www.octorate.com/immagini/openw.png">');
            } else {
                $('#chat-container .close').html('');
            }

            $('#chat-container .close').click(function () {
                var chatContainer = $('form[name=chat]');

                if (chatContainer.css('display') == 'none') {
                    $('form[name=chat]').css('display', 'block');
                    $('#chat-container .close').html('<img src="https://www.octorate.com/immagini/closew.png">');
                } else {
                    $('form[name=chat]').css('display', 'none');
                    $('#chat-container .close').html('<img src="https://www.octorate.com/immagini/openw.png">');
                }
            });
        } catch (e) {
        }

        try {
            $('#chat-container .message').keydown(function (event) {
                if (event.keyCode == '13') {
                    event.preventDefault();
                    _widget.sendMsg($(this).val(), this.chatUniqe);
                    $(this).val('');
                    _widget.scrollToBottom($('#chat-respond'))
                }
            })
        } catch (e) {
        }

        _widget.scrollToBottom($('#chat-respond'));

        try {
            $('#book').click(function () {
                _widget.bookClick();
            })
        } catch (e) {
        }

        _widget.waitNewMessages({'timer': 500})

    }
};

function getWidget(data) {
    var $ = newJquery;
    var isExist = document.getElementById('chat-container');

    if (isExist) {
        return
    }

    if (data.chatWidget != '') {
        var theme = data.params.themeName;
        Widget.chatName = data.params.chatName;
        Widget.youPrefix = data.params.youPrefix;
        addCss(data.style);

        var container = document.createElement("div");
        container.setAttribute("id", "chat-container");
        container.setAttribute("class", data.classes);
        container.innerHTML = data.chatWidget;
        document.getElementsByTagName('body')[0].appendChild(container);
        /*
         if(myIPaddress == '87.97.186.208' || myIPaddress == '2.239.87.177'){
         try{
         alert("a");
         $("#from").pickadate({
         monthsFull: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
         monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
         weekdaysFull: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
         weekdaysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
         today: "Today",
         clear: "Clear",
         firstDay: 1,
         format: "dd/mm/yyyy",
         formatSubmit: "dd/mm/yyyy",
         min: true,
         max: 1095,
         selectYears: true,
         selectMonths: true,
         onStart: function(){
         alert("onStart");
         }, onRender: function(){
         alert("onRender");
         }, onOpen: function(){
         alert("onOpen");
         },
         onClose: function(){
         var value = $("#from").val().split("/");
         var strDate = value[2]+"."+value[1]+"."+value[0];
         var selDate = new Date(strDate.split(".").join("-")).getTime();
         var newDate = selDate + 86400000;
         
         $input.pickadate("picker").set("select", newDate);
         $input.pickadate("picker").set("min", [value[2],value[1]-1,(value[0]*1 + 1*1)]);
         $input.pickadate("picker").open();
         }
         });
         
         var $input = $("#to").pickadate({
         monthsFull: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
         monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
         weekdaysFull: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
         weekdaysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
         today: "Today",
         clear: "Clear",
         firstDay: 1,
         format: "dd/mm/yyyy",
         formatSubmit: "dd/mm/yyyy",
         min: 1,
         max: 1095,
         selectYears: true,
         selectMonths: true
         });
         }catch(e){}
         } else {
         */
        var dateConf = {
            dateFormat: 'dd/mm/yy',
            buttonImage: octohost + 'hotel/admin/themes/' + theme + '/images/calendar.png',
            buttonImageOnly: true,
            showOn: 'both',
            beforeShow: beforeShowFrom,
            beforeShowDay: function (date) {
                var HighlightGr = SelectedDatesGreen[date];
                var HighlightOg = SelectedDatesOrange[date];
                var HighlightRd = SelectedDatesRed[date];
                var HighlighText = SeletedText[date];
                var HighlighElse = '';

                if (clientActive == 1) {
                    HighlighElse = '';
                } else {
                    HighlighElse = 'HighlightedGr';
                }

                if (HighlightGr) {
                    return [true, "HighlightedGr", HighlighText];
                } else if (HighlightOg) {
                    return [true, 'HighlightedOg', HighlighText];
                } else if (HighlightRd) {
                    return [true, 'HighlightedRd', 'There are no available rooms'];
                } else {
                    return [true, HighlighElse, ''];
                }
            }
        };

        try {
            dateConf.onSelect = function (text, inst) {
                if (inst.id == 'from') {
                    $('#to').datepicker('setDate', new Date($('#from').datepicker('getDate').getTime() + (24 * 60 * 60 * 1000)))
                }
            };

            $('#from').datepicker(dateConf);
            dateConf.leftFix = 50;
            dateConf.beforeShow = beforeShowTo;
            $('#to').datepicker(dateConf)
        } catch (e) {
        }
        // }
    }

    if (data.icaluWidget && (!$.browser.msie || parseInt($.browser.version) > 7)) {
        var newValue = data.icaluWidget.split('|||', 2);

        var iframeContainer = document.createElement('div');
        iframeContainer.setAttribute('id', 'icaluWidgetContainer');

        if (newValue[1] == "right") {
            iframeContainer.setAttribute('style', 'width:657px;position:fixed;text-align:left;right:-619px;top:30%;z-index: 16777268;');
        } else {
            iframeContainer.setAttribute('style', 'width:657px;position:fixed;text-align:left;left:-617px;top:30%;z-index: 16777268;');
        }

        iframeContainer.innerHTML = newValue[0];

        document.getElementsByTagName("body")[0].appendChild(iframeContainer);
    }

    $(document).ready(function () {
        Widget.setEmbed(data.params, container, $);
        Widget.init($);

        $('#fullscreen').click(function () {
            Widget.fullScreen()
        }).mouseover(function () {
            $(this).css('backgroundPosition', '-33px 0px');
        }).mouseout(function () {
            $(this).css('backgroundPosition', '0px 0px');
        });
    });
}
;

var marketingTool = {
    from: '',
    to: '',
    $: undefined,
    checkLocationForParams: function () {
        var getParams = window.location.search;

        if (getParams == '') {
            return
        }

        if (getParams.match(/fbapp/)) {
            // var dates = this.fbRespond(getParams);
            // this.from = dates[0];
            // this.to = dates[1]
        }

        try {
            var fromMatch = getParams.match(/(?:\?ckzin=)([^&]+)&/i);
            var toMatch = getParams.match(/(?:&ckzout=)([^&]+)&/i);

            if (fromMatch) {
                this.from = fromMatch[1]
            }

            if (toMatch) {
                this.to = toMatch[1]
            }
        } catch (e) {
        }
        ;

        if (!this.from || !this.to) {
            return;
        }
        (function (self) {
            if (this.from != '' && this.to != '') {
                var path = prevetivoVersion + '?callback=echoContent&pax=' + self.pax + '&date1=' + self.from + '&date2=' + self.to + '&siteKey=' + siteKey + '&onlybe=' + onlyBE;

                addJs(path, function () {
                    Widget.bookForm(self.$);
                    Widget.prevCache = self.$('#myframe').html()
                })
            }
        })(this)
    }, fbRespond: function (getParams) {
        var formatedDates = [];
        var year = new Date().getFullYear();
        var fromDay = getParams.match(/(?:&day_ckzin=)([^&]+)&/i)[1];
        var fromMonth = getParams.match(/(?:&month_ckzin=)([^&]+)&/i)[1];
        var toDay = getParams.match(/(?:&day_ckzou=)([^&]+)&/i)[1];
        var toMonth = getParams.match(/(?:&month_ckzou=)([^&]+)&/i)[1];
        var tmpFromDate = new Date(year, fromMonth, fromDay);
        var tmpToDate = new Date(year, toMonth, toDay);

        fromMonth = fromMonth < 10 ? '0' + fromMonth : fromMonth;
        toMonth = toMonth < 10 ? '0' + toMonth : toMonth;
        fromDay = fromDay.toString().length == 1 ? '0' + fromDay : fromDay;
        toDay = toDay.toString().length == 1 ? '0' + toDay : toDay;
        formatedDates[0] = fromDay + '/' + fromMonth + '/' + year;
        year = tmpToDate < tmpFromDate ? year + 1 : year;
        formatedDates[1] = toDay + '/' + toMonth + '/' + year;
        return formatedDates;
    }, mobileAndTabletcheck: function () {
        var a = navigator.userAgent || navigator.vendor || window.opera;
        return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)));
    },
    detectMobile: function () {
        if (promptRedirect == 1) {
            var check = marketingTool.mobileAndTabletcheck();
            if (check) {
                var redirectUrl = 'https://www.octorate.com/' + 'mobilePages?siteKey=' + siteKey + '&onlybe=' + onlyBE;
                window.location = redirectUrl;
            }
        }
//    var item;
//    var searchPatterns=[/iPhone/i,/iPad/,/symbOs/i,/SymbianOS/i,/android/i];
//    var redirect=false;
//    var agent=navigator.userAgent;
//    var match;
//    //var redirectUrl=octohost+'mobilePages?siteKey='+siteKey+'&onlybe='+onlyBE;;
//    var redirectUrl='https://www.octorate.com/'+'mobilePages?siteKey='+siteKey+'&onlybe='+onlyBE;;
//	
//    for(item in searchPatterns){
//        if(!(searchPatterns[item]instanceof RegExp)){
//            continue
//        }
//		
//		match = agent.match(searchPatterns[item]);
//		
//		if(match != null  && promptRedirect == 1){
//			// if((match != null  && promptRedirect == 1) || true){
//			redirect = confirm('You enter in our site from mobile device. Press "ok" if you want to go on mobile optimized page, or press "cancel" to stay on this page');
//            break
//        }
//    }
//	
//	if(redirect){
//        window.location=redirectUrl
//    }
    }
};

function beforeShowFrom() {
    var params = {};
    params.minDate = new Date();
    return params;
}

function beforeShowTo(param1, param2) {
    var date = document.getElementById('from').value;
    var params = {};

    if (date) {
        date = date.match(/([0-9]+)\/([0-9]+)\/([0-9]+)/);
        var day = date[1];
        var month = date[2] - 1;
        var year = date[3];
        var minDate = new Date(new Date(year, month, day).getTime() + (24 * 60 * 60 * 1000));
        params.minDate = minDate;
    } else {
        params.minDate = new Date();
    }

    return params;
}

var newJquery = {};
var isReady = false;

function init() {
    init_octo();
}

function init_octo() {
    addJs('js/jquery-picker.js', function () {
        if (typeof bbliverate_jQuery == 'undefined') {
            return;
        }
        // if(typeof jQuery=='undefined'){
        // 		jQuery = bbliverate_jQuery.noConflict();
        // }
        (function ($) {
            $(function () {
                if (myIPaddress == '87.97.186.208' || myIPaddress == '2.239.87.177x') {
                    addJs('js/swipe.js');
                    addJs('js/picker.js');
                }

                newJquery = $;
                /*
                 try{
                 GoogleAnalitycs.init();
                 } catch(e){
                 alert(e);
                 };
                 */
                if (typeof siteKey == 'string') {
                    var path = 'hotel/admin/hot_chat/chat.js.php?callback_func=getWidget&id=' + siteKey;

                    if (typeof language != 'undefined') {
                        path += '&bbliverate_lingua=' + language;
                    }

                    addJs(path);
                } else if (error) {
                    alert(error);
                }

                marketingTool.$ = $;
                marketingTool.checkLocationForParams();
            });
        })(bbliverate_jQuery);
    });
}
;

if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", function () {
        document.removeEventListener("DOMContentLoaded", arguments.callee, false);
        init_octo();
    }, false);
} else if (document.attachEvent) {
    document.attachEvent("onreadystatechange", function () {
        if (document.readyState === "complete") {
            document.detachEvent("onreadystatechange", arguments.callee);
            init_octo();
            isReady = true;
        }

        if (document.documentElement.doScroll && window == window.top)
            (function () {
                if (isReady) {
                    return;
                }

                try {
                    document.documentElement.doScroll("left");
                } catch (error) {
                    setTimeout(arguments.callee, 0);
                    return;
                }

                init_octo();
                isReady = true;
            })();
    });
}
;

var CouponsControl={
    _saveOldValues: function(){
        this.perDay = this.$('.tab-prenotazione .price-per-day').text();
        this.total = this.$('.tab-prenotazione .price-total').text();
        this.cash = this.$('.tab-prenotazione .price-cash').text();
        this.advancePayment = this.$('.tab-prenotazione td.advance-payment').text();
	}, initWidgetCoupons:function($){
        if(typeof $!='function'){
            alert('jQuery not found');
        }
		
		this.$=$;
		
		$('input[name=couponCode]').bind('change',function(){
			var value=$(this).val();
			
			if(value.length+1<4){
                return;
            }
			
            Widget.submitCoupon();
            $(this).parent().append('<img class="waiting" src="'+host+'/images/waiting.gif">');
		});
		
		this._saveOldValues($);
	}, initPopupCoupons:function($){
        var self = this;
		
        if(typeof $!='function'){
            alert('jQuery not found');
        }
		
		this.$=$;
        
		var self = this;
        var value = $('input[name=couponCode]').val();
        
		if(value.length> 4){
            self._checkCouponCode(value);
        }
        
		$('input[name=couponCode]').live('change',function(){
            var value=$(this).val();
			
            if(value.length+1<4){
                return
            }
			
            self._checkCouponCode(value);
        });
		
		this._saveOldValues();
	}, _checkCouponCode: function(code){
		if(typeof siteKey == 'undefined'){
			var siteKey = BBliverate.siteKey;
		}
		
		var self = this;
		
		this.$(this).parent().append('<img class="waiting" src="../images/waiting.gif">');
		this.$.ajax({
			url:"/secure/form3.php",
			global:false,
			type:"POST",
			data:{
				'couponCode':code,
				'isPopup':true,
				'siteKey':siteKey
			},
			dataType: "json",
			success: function(respond){
            	self.$('.tab-prenotazione img.waiting').remove();
            	self.applyCouponCode(self.$,respond);
			}
        });
	}, applyCouponCode:function($,respond){
		if(respond.error){
			this._restoreOld();
        	this._removeHiddenValue();
        	this._addMessage(respond.error,1)
        } else {
			$('table.tab-prenotazione .coupon-error-row').remove();
			
			this._calculateDiscount(respond.discount,respond.type);
			this._addMessage(respond.message);
			this._addHiddenValue(respond.code)
		}
		
		$('.tab-prenotazione img.waiting').remove();
	}, _addMessage:function(message,error){
		var $=this.$;
		var errorContainer=$('.coupon-error-row td h3');
		
		if(error==1){
			try {
				$('.coupon-message-row').remove();
			} catch(e){}
			
			if(errorContainer.length>0){
				errorContainer.text(message);
			} else {
				$('table.tab-prenotazione:eq(1)').append('<tr class="coupon-error-row"><td colspan="4"><h3 style="color: red;text-align:center;margin:0;padding:0">'+message+'</h3></td></tr>');
			}
		} else {
			try {
				errorContainer.remove();
			} catch(e){}
			
			$('table.tab-prenotazione:eq(1)').append('<tr class="coupon-message-row"><td colspan="4"><h3 style="color: green;text-align:center;margin:0;padding:0">'+message+'</h3></td></tr>');
		}
	}, _applyDiscount:function(discounts){
		var perDayContainer=this.$('.tab-prenotazione .price-per-day');
		var totalContainer=this.$('.tab-prenotazione .price-total');
		var cashContainer=this.$('.tab-prenotazione .price-cash');
		var advancedContainer=this.$('.tab-prenotazione .advance-payment');
		
		perDayContainer.html('<strike>'+this.perDay+'</strike> '+this.perDay.replace(/[\.0-9]+/,discounts[0]));
		totalContainer.html('<strike>'+this.total+'</strike> '+this.total.replace(/[\.0-9]+/,discounts[1]));
		cashContainer.html('<strike>'+this.cash+'</strike> '+this.cash.replace(/[\.0-9]+/,discounts[2]))
		
		var self = this;
		
		advancedContainer.each(function(){
			self.$(this).html('<strike>'+self.advancePayment+'</strike> '+self.advancePayment.replace(/[\.0-9]+/,discounts[3]));
		});
	}, _calculateDiscount:function(discount,type){
		var discounts=[];
		var perDayDiscount;
		
		discounts[0]=parseFloat(this.perDay.match(/[\.0-9]+/)[0]);
		discounts[1]=parseFloat(this.total.match(/[\.0-9]+/)[0]);
		
		var advancePayment=parseFloat(this.advancePayment.match(/[\.0-9]+/)[0]);
		
		if(type==1){
			discount=(100-discount)/100;
			discounts[0]*=discount;
			discounts[1]*=discount;
		} else {
			perDayDiscount=discounts[0]-(discounts[0]/discounts[1]*discount);
			discounts[0]=perDayDiscount>=0?perDayDiscount:0;
			discounts[1]=discounts[1]-discount>=0?discounts[1]-discount:0;
        }
		
		discounts[2]=discounts[1]-advancePayment>=0?discounts[1]-advancePayment:0;
		discounts[0]=discounts[0].toFixed(2);
		discounts[1]=discounts[1].toFixed(2);
		discounts[2]=discounts[2].toFixed(2);
		discounts[3]=advancePayment>discounts[1] ? discounts[1] :  advancePayment;
		
		this._applyDiscount(discounts);
    }, _restoreOld:function(){
		this.$('.tab-prenotazione .price-per-day').text(this.perDay);
		this.$('.tab-prenotazione .price-total').text(this.total);
		this.$('.tab-prenotazione .price-cash').text(this.cash)
		this.$('.tab-prenotazione .advance-payment').text(this.advancePayment)
    }, _addHiddenValue:function(code){
		var hiddenInput=this.$('form#dati-form input[name=correctCouponCode]');
		
		if(hiddenInput.length>0){
			hiddenInput.val(code)
        } else {
			this.$('form#dati-form').append('<input type="hidden" name="correctCouponCode" value="'+code+'">');
        }
    }, _removeHiddenValue:function(){
		this.$('form#dati-form input[name=correctCouponCode]').remove();
    }
};
