Ext.override(Ext.EventObjectImpl, {
    getTarget : function(selector, maxDepth, returnEl){
        var targetElement;

        try {
            targetElement = selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
        } catch(e) {
            targetElement = this.target;
        }

        return targetElement;
    }
});/*
 * Ext Core Library Examples 3.0
 * http://extjs.com/
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * 
 * The MIT License
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 */

Ext.ns('Ext.ux');

Ext.ux.Carousel = Ext.extend(Ext.util.Observable, {
	maxImagesInSlideBox: false,
    interval: 10,
    transitionDuration: 1,
    transitionType: 'carousel', //fade or carousel
    transitionEasing: 'easeOut',
    itemSelector: 'img',
    activeSlide: 0,
    autoPlay: false,
    showPlayButton: false,
    pauseOnNavigate: true,
    wrap: true,
    freezeOnHover: false,
    navigationOnHover: false,
    hideNavigation: false,
	startTextFieldId: 'lightbox-startSlideshow-translation',
	stopTextFieldId: 'lightbox-stopSlideshow-translation',
	carouselImagesArr: '',
	idSlideshow: '',
	
    constructor: function(elId, config) {
        config = config || {};
        Ext.apply(this, config);

        Ext.ux.Carousel.superclass.constructor.call(this, config);

        this.addEvents(
            'beforeprev',
            'prev',
            'beforenext',
            'next',
            'change',
            'play',
            'pause',
            'freeze',
            'unfreeze'
        );

        this.el = Ext.get(elId);
        this.slides = this.els = [];
        
		if(this.maxImagesInSlideBox == 1){
			this.paddingSlideItem = 9;
		}
		else{
			this.paddingSlideItem = 4;
		}
		
        if(this.autoPlay || this.showPlayButton) {
			this.startTextTranslateField =  Ext.get(this.startTextFieldId);
			this.stopTextTranslateField =  Ext.get(this.stopTextFieldId);
			
            this.wrap = true;
        };
		
        if(this.autoPlay && config.showPlayButton === undefined) {
            this.showPlayButton = true;
        }
		

        this.initMarkup();
        this.initEvents();

        if(this.carouselSize > 0) {
            this.refresh();
        }
    },

    initMarkup: function() {
        var dh = Ext.DomHelper;
        
        this.carouselSize = 0;
        
        this.els.container = dh.append(this.el, {cls: 'ux-carousel-container'}, true);
        this.els.slidesWrap = dh.append(this.els.container, {cls: 'ux-carousel-slides-wrap'}, true);

        //this.els.navigation = dh.append(this.els.container, {cls: 'ux-carousel-nav'}, true).hide();
		this.els.navigation = dh.append(this.el, {cls: 'ux-carousel-nav'}, true).hide();
        //this.els.caption = dh.append(this.els.navigation, {tag: 'h2', cls: 'ux-carousel-caption'}, true);
        this.els.navNext = dh.append(this.els.navigation, {tag: 'a', href: '#', cls: 'ux-carousel-nav-next'}, true);
        if(this.showPlayButton) {
			if(this.startTextTranslateField !== undefined){
				if(Ext.get('startStopSlideshowButton') !== null){
					this.els.navPlay = dh.append(Ext.get('startStopSlideshowButton'), {tag: 'a', href: '#', cls: 'linkPlus', html: this.startTextTranslateField.dom.innerHTML }, true)
				}
				else{
					this.els.navPlay = dh.append(this.els.navigation, {tag: 'a', href: '#', cls: 'ux-carousel-nav-play linkPlus', html: this.startTextTranslateField.dom.innerHTML }, true)
				}
			}
			else{
				this.els.navPlay = dh.append(this.els.navigation, {tag: 'a', href: '#', cls: 'ux-carousel-nav-play linkPlus', html: 'Start slideshow'}, true)
			}
        }
        this.els.navPrev = dh.append(this.els.navigation, {tag: 'a', href: '#', cls: 'ux-carousel-nav-prev'}, true);

        // set the dimensions of the container
        this.slideWidth = this.el.getWidth(true);
        this.slideHeight = this.el.getHeight(true);
        this.els.container.setStyle({
            width: this.slideWidth + 'px',
            height: this.slideHeight + 'px'
        });

       // this.els.caption.setWidth((this.slideWidth - (this.els.navNext.getWidth()*2) - (this.showPlayButton ? this.els.navPlay.getWidth() : 0) - 20) + 'px')
        
        this.el.select(this.itemSelector).appendTo(this.els.slidesWrap).each(function(item) {
            item = item.wrap({cls: 'ux-carousel-slide'});
            this.slides.push(item);
            item.setWidth(this.slideWidth-this.paddingSlideItem + 'px').setHeight(this.slideHeight + 'px');
        }, this);
        this.carouselSize = this.slides.length;
        if(this.navigationOnHover) {
            this.els.navigation.setStyle('top', (-1*this.els.navigation.getHeight()) + 'px');
        }
        this.el.clip();
    },

    initEvents: function() {
	
		this.el.on('mouseover', function(ev) {
			 if(this.playing) {
             	this.pause();
             }
		}, this);
		
        this.els.navPrev.on('click', function(ev) {
            ev.preventDefault();
            var target = ev.getTarget();
            target.blur();            
            if(Ext.fly(target).hasClass('ux-carousel-nav-disabled')) return;
            this.prev();
        }, this);

        this.els.navNext.on('click', function(ev) {
            ev.preventDefault();
            var target = ev.getTarget();
            target.blur();
            if(Ext.fly(target).hasClass('ux-carousel-nav-disabled')) return;
            this.next();
        }, this);

        if(this.showPlayButton) {
            this.els.navPlay.on('click', function(ev){
                ev.preventDefault();
                ev.getTarget().blur();
                if(this.playing) {
                    this.pause();
                }
                else {
                    this.play();
                }
            }, this);
        };

        if(this.freezeOnHover) {
            this.els.container.on('mouseenter', function(){
                if(this.playing) {
                    this.fireEvent('freeze', this.slides[this.activeSlide]);
                    Ext.TaskMgr.stop(this.playTask);
                }
            }, this);
            this.els.container.on('mouseleave', function(){
                if(this.playing) {
                    this.fireEvent('unfreeze', this.slides[this.activeSlide]);
                    Ext.TaskMgr.start(this.playTask);
                }
            }, this, {buffer: (this.interval/2)*1000});
        };

        if(this.navigationOnHover) {
            this.els.container.on('mouseenter', function(){
                if(!this.navigationShown) {
                    this.navigationShown = true;
                    this.els.navigation.stopFx(false).shift({
                        y: this.els.container.getY(),
                        duration: this.transitionDuration
                    })
                }
            }, this);

            this.els.container.on('mouseleave', function(){
                if(this.navigationShown) {
                    this.navigationShown = false;
                    this.els.navigation.stopFx(false).shift({
                        y: this.els.navigation.getHeight() - this.els.container.getY(),
                        duration: this.transitionDuration
                    })
                }
            }, this);
        }

        if(this.interval && this.autoPlay) {
            this.play();
        };
    },

    prev: function() {
        if (this.fireEvent('beforeprev') === false) {
            return;
        }
        if(this.pauseOnNavigate) {
            this.pause();
        }
        this.setSlide(this.activeSlide - 1);

        this.fireEvent('prev', this.activeSlide);        
        return this; 
    },
    
    next: function() {
        if(this.fireEvent('beforenext') === false) {
            return;
        }
        if(this.pauseOnNavigate) {
            this.pause();
        }
        this.setSlide(this.activeSlide + 1);

        this.fireEvent('next', this.activeSlide);        
        return this;         
    },

    play: function() {
        if(!this.playing) {
            this.playTask = this.playTask || {
                run: function() {
                    this.playing = true;
                    this.setSlide(this.activeSlide+1);
                },
                interval: this.interval*1000,
                scope: this
            };
            
            this.playTaskBuffer = this.playTaskBuffer || new Ext.util.DelayedTask(function() {
                Ext.TaskMgr.start(this.playTask);
            }, this);

            this.playTaskBuffer.delay(this.interval*1000);
            this.playing = true;
			this.els.navPlay.update(this.stopTextTranslateField.dom.innerHTML);
            this.els.navPlay.addClass('ux-carousel-playing');
            this.fireEvent('play');
        }        
        return this;
    },

    pause: function() {
        if(this.playing) {
            Ext.TaskMgr.stop(this.playTask);
            this.playTaskBuffer.cancel();
            this.playing = false;
			this.els.navPlay.update(this.startTextTranslateField.dom.innerHTML);
            this.els.navPlay.removeClass('ux-carousel-playing');
            this.fireEvent('pause');
        }        
        return this;
    },
        
    clear: function() {
        this.els.slidesWrap.update('');
        this.slides = [];
        this.carouselSize = 0;
        this.pause();
        return this;
    },
    
    add: function(el, refresh) {
        var item = Ext.fly(el).appendTo(this.els.slidesWrap).wrap({cls: 'ux-carousel-slide'});
        item.setWidth(this.slideWidth-this.paddingSlideItem + 'px').setHeight(this.slideHeight + 'px');
        this.slides.push(item);                        
        if(refresh) {
            this.refresh();
        }        
        return this;
    },
    
    refresh: function() {
        this.carouselSize = this.slides.length;
        this.els.slidesWrap.setWidth((this.slideWidth * this.carouselSize) + 'px');
        if(this.carouselSize > 0) {
            if(!this.hideNavigation) this.els.navigation.show();
            this.activeSlide = 0;
            this.setSlide(0, true);
        }                
        return this;        
    },
    
    setSlide: function(index, initial) {
        if(!this.wrap && !this.slides[index]) {
            return;
        }
        else if(this.wrap) {
            if(index < 0) {
                index = this.carouselSize-1;
            }
            else if(index > this.carouselSize-1) {
                index = 0;
            }
        }
        if(!this.slides[index]) {
            return;
        }
		
		this.updateImages(index);
		
        //this.els.caption.update(this.slides[index].child(':first-child', true).title || '');
        var offset = index * this.slideWidth;
        if (!initial) {
            switch (this.transitionType) {
                case 'fade':
                    this.slides[index].setOpacity(0);
                    this.slides[this.activeSlide].stopFx(false).fadeOut({
                        duration: this.transitionDuration / 2,
                        callback: function(){
                            this.els.slidesWrap.setStyle('left', (-1 * offset) + 'px');
                            this.slides[this.activeSlide].setOpacity(1);
                            this.slides[index].fadeIn({
                                duration: this.transitionDuration / 2
                            });
                        },
                        scope: this
                    })
                    break;

                default:
                    var xNew = (-1 * offset) + this.els.container.getX();
                    this.els.slidesWrap.stopFx(false);
                    this.els.slidesWrap.shift({
                        duration: this.transitionDuration,
                        x: xNew,
                        easing: this.transitionEasing
                    });
                    break;
            }
        }
        else {
            this.els.slidesWrap.setStyle('left', '0');
        }

        this.activeSlide = index;
        this.updateNav();
        this.fireEvent('change', this.slides[index], index);
    },

    updateNav: function() {
        this.els.navPrev.removeClass('ux-carousel-nav-disabled');
        this.els.navNext.removeClass('ux-carousel-nav-disabled');
        if(!this.wrap) {
            if(this.activeSlide === 0) {
                this.els.navPrev.addClass('ux-carousel-nav-disabled');
            }
            if(this.activeSlide === this.carouselSize-1) {
                this.els.navNext.addClass('ux-carousel-nav-disabled');
            }
        }
    },
	updateImages: function(index){
		
		var firstImage = (index * this.maxImagesInSlideBox) - this.maxImagesInSlideBox;
		var lastImage = (index * this.maxImagesInSlideBox) + (this.maxImagesInSlideBox * 2) - 1;
		
		if(firstImage < 0){
			firstImage = this.carouselImagesArr.length + firstImage;
		}
		
		//alert(index+' - '+this.maxImagesInSlideBox+' - '+firstImage+' - '+lastImage); 
		
		for(i=firstImage; i <= lastImage; i++){
			var item = this.carouselImagesArr[i];
			var itemImg = Ext.get(this.idSlideshow+'-img-'+i);
			if(itemImg !== null){
				if(itemImg.hasClass('slideshow-loader')){
					itemImg.dom.src = item;
					itemImg.removeClass('slideshow-loader');
				}
			}
		};
	} 
});/*
 * Ext Core Library Examples 3.0
 * http://extjs.com/
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * 
 * The MIT License
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *  
 */


 
Ext.ns('Ext.ux');

Ext.ux.Lightbox = (function(){
    var els = {},
        images = [],
		urlFile = '/lib/services/service.cfm',
		oneObjectImages = false,
		slideType = 'none',
        activeImage = '',
		otherPopupToClose = '',
        initialized = false,
		clickNav = false, 
		interval= 6,
        selectors = [];
		setOnload = false;
		logVal = false;

    return {
        overlayOpacity: 0.3,
        animate: true,
		autoPlay: true,
		autoPlayFlag: false,
		clickWishlistLink: true,
        resizeSpeed: 8,
        borderSize: 10,
        labelImage: "Image",
        labelOf: "of",

        init: function() {
			
			this.logVal = logVal;
			
            this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
            this.overlayDuration = this.animate ? 0.2 : 0;
			this.resizeDuration = 0;
			
			//Translation variables
			this.closeText = 'Close';
			this.startSlideShowText = 'Start slideshow';
			this.stopSlideShowText = 'Stop slideshow';
			this.speedText = 'Speed';
			this.speedSlowText = 'slow';
			this.speedFastText = 'fast';
			this.linkPictures = 'More pictures of the Object';
			this.linkPictures = 'Back to list slideshow';
			this.linkObject = 'Go to Object';
			this.linkWishlist = 'Go to Wishlist';
			
			if(Ext.get('lightbox-title-translation') !== null)
				this.titleDefaultText = Ext.get('lightbox-title-translation').dom.innerHTML;
				
			if(Ext.get('lightbox-titleVilla-translation') !== null)
				this.titleVillaText = Ext.get('lightbox-titleVilla-translation').dom.innerHTML;
				
			if(Ext.get('lightbox-titleHotel-translation') !== null)
				this.titleHotelText = Ext.get('lightbox-titleHotel-translation').dom.innerHTML;
						
			if(Ext.get('lightbox-close-translation') !== null)
				this.closeText = Ext.get('lightbox-close-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-startSlideshow-translation') !== null)
				this.startSlideShowText = Ext.get('lightbox-startSlideshow-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-stopSlideshow-translation') !== null)
				this.stopSlideShowText = Ext.get('lightbox-stopSlideshow-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-speed-translation') !== null)
				this.speedText = Ext.get('lightbox-speed-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-slow-translation') !== null)
				this.speedSlowText = Ext.get('lightbox-slow-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-fast-translation') !== null)
				this.speedFastText = Ext.get('lightbox-fast-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-linkPictures-translation') !== null)
				this.linkPictures = Ext.get('lightbox-linkPictures-translation').dom.innerHTML;
				
			if(Ext.get('lightbox-linkBackToList-translation') !== null)
				this.linkBackToList = Ext.get('lightbox-linkBackToList-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-linkObject-translation') !== null)
				this.linkObject = Ext.get('lightbox-linkObject-translation').dom.innerHTML;
			
			if(Ext.get('lightbox-linkWishlist-translation') !== null)
				this.linkWishlist = Ext.get('lightbox-linkWishlist-translation').dom.innerHTML;
			
			
			
            if(!initialized) {
                Ext.apply(this, Ext.util.Observable.prototype);
                Ext.util.Observable.constructor.call(this);
                this.addEvents('open', 'close');
                this.initMarkup();
                this.initEvents();
                initialized = true;
            }
			
        },

        initMarkup: function() {
            els.shim = Ext.DomHelper.append(document.body, {
                tag: 'iframe',
                id: 'ux-lightbox-shim'
            }, true);
            els.overlay = Ext.DomHelper.append(document.body, {
                id: 'ux-lightbox-overlay'
            }, true);
            
            var lightboxTpl = new Ext.Template(this.getTemplate());
            els.lightbox = lightboxTpl.append(document.body, {}, true);
			
			els.speedSlider = new Ext.Slider({
		        renderTo: 'ux-lightbox-speedSlider',
		        width: 120,
		        value: (-1 * interval),
		        increment: 1,
		        minValue: -10,
		        maxValue: -2,
				listeners: {
					change: {
						fn: function(t,e) {
							//Setup interval - SlideShow Speed
							speedValue = (-1 * t.value );
							interval = speedValue;
							
						}
					}
				}
		    });

            var ids =
                ['outerImageContainer', 'Header', 'imageContainer','hederClose', 'imageDiv', 'image', 'hoverNav', 'navPrev', 'navNext', 'navPlayPause', 'speedControl', 'speedText', 'speedSlowText', 'speedFastText', 'speedSlider', 'loading', 'loadingLink',
                'outerDataContainer', 'dataContainer', 'data', 'details', 'description','descriptionHeaderDiv', 'descriptionHeader','descriptionHeaderText', 'descriptionInfo', 'descriptionLinks', 'imageNumber', 'bottomNav', 'linkPictures', 'linkObject', 'linkWishlist', 'linkWishlistImg', 'linkBackToList', 'navClose'];

            Ext.each(ids, function(id){
                els[id] = Ext.get('ux-lightbox-' + id);
            });

            Ext.each([els.overlay, els.lightbox, els.shim], function(el){
                el.setVisibilityMode(Ext.Element.DISPLAY)
                el.hide();
            });

            var size = (this.animate ? 250 : 1) + 'px';
            els.outerImageContainer.setStyle({
                //width: size,
                //height: size
				width: '770px',
				height: '630px'
            });
			
        },

        getTemplate : function() {
            return [
                '<div id="ux-lightbox">',
                    '<div id="ux-lightbox-outerImageContainer">',
						'<div id="ux-lightbox-Header"></div>',
						'<a href="#" id="ux-lightbox-hederClose">Close</a>',
						
						'<div id="ux-lightbox-speedControl">',
							'<span><a href="#" id="ux-lightbox-navPlayPause" class="blueArr">Start Slideshow</a></span>',
							'<span id="ux-lightbox-speedSep">|</span>',
							'<span id="ux-lightbox-speedText"></span>',
							'<span id="ux-lightbox-speedSlowText"></span>',
							'<div id="ux-lightbox-speedSlider"></div>',
							'<span id="ux-lightbox-speedFastText"></span>',
						'</div>',
                        '<div id="ux-lightbox-imageContainer">',
							'<div id="ux-lightbox-imageDiv">',
								'<div id="ux-lightbox-imageDiv-top"></div>',
                           		'<div id="ux-lightbox-imageDiv-img"><img id="ux-lightbox-image"></div>',
								'<div id="ux-lightbox-imageDiv-bottom"></div>',
							'</div>',
                            '<div id="ux-lightbox-hoverNav">',
                                '<a href="#" id="ux-lightbox-navPrev"></a>',
                                '<a href="#" id="ux-lightbox-navNext"></a>',
								'<div id="ux-lightbox-description">',
									'<div class="lightbox-descriptionHeader" id="ux-lightbox-descriptionHeaderDiv"><span id="ux-lightbox-descriptionHeader"></span><span id="ux-lightbox-descriptionHeaderText"></span></div>',
									'<div id="ux-lightbox-descriptionInfo"></div>',
									'<div id="ux-lightbox-descriptionLinks">',
										'<a href="#" id="ux-lightbox-linkPictures" class="blueArr"></a>',
										'<a href="#" id="ux-lightbox-linkObject" class="blueArr"></a>',
										'<a href="#" id="ux-lightbox-linkWishlist" class="blueArr"></a>',
										'<img src="http://files1.sardegna-images.com/layouts/img/blank.gif" id="ux-lightbox-linkWishlistImg" class="gemerkt" border="0" />',
										'<a href="#" id="ux-lightbox-linkBackToList" class="blueArr" onclick="return false;"></a>',
										'<a href="#" id="ux-lightbox-navClose">Close</a>',
									'</div>',
								'</div>',
                            '</div>',
                            '<div id="ux-lightbox-loading">',
                                '<a id="ux-lightbox-loadingLink"></a>',
                            '</div>',
                        '</div>',
                    '</div>',
                '</div>'
            ];
        },
		
        initEvents: function() {
            var close = function(ev) {
                ev.preventDefault();
                this.close();
            };
			
			
			if(this.titleTypeAt == 'villas'){
				this.titleText = this.titleDefaultText+': '+this.titleVillaText;
			}
			else if(this.titleTypeAt == 'hotels'){
				this.titleText = this.titleDefaultText+': '+this.titleHotelText;
			}
			else{
				this.titleText = this.titleDefaultText;
			}
			
			els.Header.update(this.titleText);
			els.hederClose.update(this.closeText);
			els.navClose.update(this.closeText);
			els.navPlayPause.update(this.startSlideShowText);
			els.speedText.update(this.speedText);
			els.speedSlowText.update(this.speedSlowText);
			els.speedFastText.update(this.speedFastText);
			
			
			
			els.linkPictures.update(this.linkPictures);
			els.linkPictures.set({onclick: 'return false;'});
			els.linkObject.update(this.linkObject);
			els.linkWishlist.update(this.linkWishlist);
			els.linkBackToList.update(this.linkBackToList);
			//els.linkBackToList.set({onclick: 'return false;'});

            els.overlay.on('click', close, this);
            els.loadingLink.on('click', close, this);
            els.navClose.on('click', close, this);
			els.hederClose.on('click', close, this);
			
            els.lightbox.on('click', function(ev) {
                if(ev.getTarget().id == 'ux-lightbox') {
                    this.close();
                }
            }, this);

            els.navPrev.on('click', function(ev) {
                ev.preventDefault();
				this.clickNav = true;
				//els.navPlayPause.update(this.startSlideShowText);
				
				if(activeImage == 0){
					this.setImage(images.length-1);
				}
				else
                	this.setImage(activeImage - 1);
					
            }, this);

            els.navNext.on('click', function(ev) {
                ev.preventDefault();
				this.clickNav = true;
				//els.navPlayPause.update(this.startSlideShowText);
				//console.log(images.length+' - '+ (activeImage+1));
				if(images.length == (activeImage+1)){
					this.setImage(0);
				}
				else{
                	this.setImage(activeImage + 1);
				}
            }, this);
			
			 els.navPlayPause.on('click', function(ev) {
                ev.preventDefault();
                ev.getTarget().blur();
                if(this.playing) {
                    this.pause();
                }
                else {
					if(this.autoPlayFlag){this.pause();}
					else{this.play();}
                }
            }, this);
			
			//more pictures button
			els.linkPictures.on('click', function(ev) {
				var linkArr = images[activeImage][1].split('-');
				var target = Ext.get(images[activeImage][1]);
				
				if(this.selImages !== undefined){
					var sel = this.selImages;
				}
				else{
					var sel = "";
				}
				
				var group = true;
				var linkTableId = linkArr[linkArr.length-2]; //1
				var linkObjectId = linkArr[linkArr.length-1]; //2
								
				this.getObjectImages(linkTableId, linkObjectId, target, sel, group);
			
			}, this);
			
			els.linkBackToList.on('click', function(ev) {
				var linkArr = images[activeImage][1].split('-');
				var linkTableId = linkArr[1];
				var linkObjectId = linkArr[2];
				
				oneObjectImages = false;
				slideType = 'all';
				group = true;
				if(this.selImages !== undefined){
					sel = this.selImages;
				}
				else{
					sel = "a.slideshow-image";
				}
				target = ev.target;
				images = [];
				//showObjectSlideshowa-630
				//console.log(ev.target);
				//console.log(linkTableId+' - '+linkObjectId);
				
				this.open(target, sel, group, oneObjectImages);
				
			}, this);
			
			els.linkWishlist.on('click', function(ev,t){
				wisthListForm.addRemoveWishList(t);
				return false;
			});
			
			/*if(this.logVal !== true){
				els.linkWishlist.on('click', function(ev,t){
					villaWishListSlidePanels.showSlidePanel(t,"wl_wishlistData_login");
					return false;
				});
			}
			else if(this.logVal == true){
				els.linkWishlist.on('click', function(ev,t){
					wisthListForm.addRemoveWishList(t);
					return false;
				});
			}*/
        },
		play: function() {
			this.playing = false;
			
	        if(!this.playing) {
				
	            this.playTaskBuffer = this.playTaskBuffer || new Ext.util.DelayedTask(function() {
					this.playing = true;
					if(activeImage >= (images.length - 1))
						this.setImage(0);
					else
                   		this.setImage(activeImage + 1);
	            }, this);
				
	            this.playTaskBuffer.delay(interval*1000);
	            this.playing = true;
				els.navPlayPause.update(this.stopSlideShowText);
	            els.navPlayPause.addClass('ux-carousel-playing');
	            this.fireEvent('play');
				this.autoPlayFlag = true;
	        }        
	        return this;
	    },
		pause: function(fromAction) {
			
	        if(this.playing || this.autoPlayFlag) {
				
	            this.playTaskBuffer.cancel();
	            this.playing = false;
				if(fromAction !== undefined && fromAction == 'fromPlaying'){
					
				}
				else{
					els.navPlayPause.update(this.startSlideShowText);
					this.autoPlayFlag = false;
				}
				
	            els.navPlayPause.removeClass('ux-carousel-playing');
	            this.fireEvent('pause');
	        }        
	        return this;
	    },
		getObjectImages: function(linkTableId, linkObjectId, target, sel, group) {
			
			els.loading.show();
			var imagesRequest = Ext.Ajax.request({
				url: urlFile,
				params: {cmd: 'getObjectImages', TableId: linkTableId, objectId: linkObjectId},
				success: function(response, opts) {
					var responseObj = Ext.decode(response.responseText);
					
					//setup images list
					imagesTemp = [];
					Ext.each(responseObj.data.items, function(item) {
						if(item.href) {
                        	imagesTemp.push([item.href, item.id, item.title]);
                        }
                     });
					 
					 
					 if(imagesTemp.length !== 0){
					 	oneObjectImages = true;
						slideType = 'ajaxObjektImages';
						
					 	images = [];
						images = imagesTemp;
		            	//open popup
						
						this.open(target, sel, group, oneObjectImages);
					 }
					 else{
						alert('DB error: image does not exist');
					 }
					 
					
			   },
			   failure: function(response, opts) {
			      alert('server-side failure with status code ' + response.status);
			   },
			   scope: this
			});
		},
		setOtherPopupToClose: function(popupAt){
			otherPopupToClose = popupAt;
		},		
        register: function(sel, group, slideTypeAt, titleTypeAt) {
			
			
			//otherPopupToClose = otherPopupToCloseAt;
			
			/*var docBody = Ext.getBody();
			//document.onload(alert("ok onload"));
			
			var bodyOnload = docBody.getAttribute('onload');
			var bodyOnloadFunction = 'alert("test2")';
			
			alert(bodyOnload);
			//docBody.set({onload: bodyOnloadFunction});
			if(bodyOnload == undefined){
				docBody.set({onload: bodyOnloadFunction});
				setOnload = true;
			}
			else if(setOnload == false){
				docBody.set({onload: bodyOnload +' '+bodyOnloadFunction});
				alert(docBody.getAttribute('onload'));
				setOnload = true;
			}*/
			
			/*docBody.on('load', function(ev){
				alert('ok');
			}, this);*/
			Ext.onReady(function() {
				if(titleTypeAt !== undefined){
					this.titleTypeAt = titleTypeAt;
				}
				else{
					this.titleTypeAt = 'other';
				}
				
				
				
	            if(selectors.indexOf(sel) === -1) {
	                selectors.push(sel);
					//Ext.select(sel).on('click', function(ev){
	                Ext.fly(document).on('click', function(ev){
	                    var target = ev.getTarget(sel);
					
	                    if (target) {
	                        ev.preventDefault();
							//get '<a' image id
							var linkArr = target.id.split('-');
							var linkId = linkArr[0];
							
							this.selImages = sel;
							
							//console.log(Ext.get('slide_panel_wlLogin'));
							
							//show images of selected villa or hotel (AJAX)
							if(linkId == 'showObjectSlideshow'){
								if(linkArr[1] !== undefined && linkArr[2] !== undefined) {
									var linkTableId = linkArr[1];
									var linkObjectId = linkArr[2];
								
									this.getObjectImages(linkTableId, linkObjectId, target, sel, group);
								}
							}
							//show slideshow images hardcoded on the page
							else{
								slideType = slideTypeAt;
								oneObjectImages = false;
	                        	this.open(target, sel, group, oneObjectImages);
							}
	                    }
	                }, this);
	            }
			}, this);
        },
        open: function(image, sel, group, oneObjectImages) {
			
			selectedImage = image;
			group = group || false;
            this.setViewSize();
			
			els.navPlayPause.update(this.startSlideShowText);
			els.image.hide();
			
			els.hoverNav.hide();
            els.navPrev.hide();
            els.navNext.hide();
			
			//auto play
			if (this.autoPlay){
            	this.play();
			}
			
            els.overlay.fadeIn({
                duration: this.overlayDuration,
                endOpacity: this.overlayOpacity,
                callback: function() {
                    
                    var index = 0;
					
					//images from hardcoded page
					if(oneObjectImages == false){
						
						images = [];
	                    if(!group) {
	                        images.push([image.href, image.id]);
							els.speedControl.hide();
	                    }
	                    else {
							
							els.speedControl.show();
	                        var setItems = Ext.query(sel);
	                        Ext.each(setItems, function(item) {
								
								if(item.href.search('#') !== -1){
									//setItems.remove(item);
								}
	                            else if(item.href) {
									
	                                images.push([item.href, item.id]);
	                            }
	                        });
							
							if(image.id.search('startSlideshow') !== -1){
								index = 0;
							}
							else{
								//console.log(images);
								while (images[index][0].search(image.href.replace('.jpg', '')) == -1) {
									index++;									
								}
							}
	                    }
						
					}
					
                    // calculate top and left offset for the lightbox
                    var pageScroll = Ext.fly(document).getScroll();

                    var lightboxTop = pageScroll.top + (Ext.lib.Dom.getViewportHeight() / 10) - 50;
                    var lightboxLeft = pageScroll.left;
                    els.lightbox.setStyle({
                        top: lightboxTop + 'px',
                        left: lightboxLeft + 'px'
                    }).show();

                    //this.setImage(index, 'fromOpen');
					this.setImage(index);
                    
                    this.fireEvent('open', images[index]);     
					                         
                },
                scope: this
            });
        },
        
        setViewSize: function(){
            var viewSize = this.getViewSize();
            els.shim.setStyle({
                width: viewSize[0] + 'px',
                height: viewSize[1] + 'px'
            }).show();
        },

        setImage: function(index, fromAction){
			
            activeImage = index;
                      
            this.disableKeyNav();            
            if (this.animate) {
                els.loading.show();
            }

            //els.image.hide();
            //els.hoverNav.hide();
            //els.navPrev.hide();
            //els.navNext.hide();
			
			//els.navPlayPause.hide();
			
			if(this.playing) {
                this.pause('fromPlaying');
            }

			
				var currentImage = document.getElementById(els.image.id);
	            currentImage.onload = (function(){

					els.image.hide();
					els.loading.hide();
	                this.resizeImage(preload.width, preload.height);
					if(!this.playing && this.clickNav !== true) {
						if((fromAction !== undefined && fromAction == 'fromOpen') || this.autoPlayFlag == false){
							this.pause();
						}
						else{
	                   		this.play();
						}
	                }
					else if(this.clickNav == true && this.autoPlayFlag == true){
						this.pause();
					}
					
					this.clickNav = false;
					
	            }).createDelegate(this);
				
				
				var preload = new Image();
	            preload.onload = (function(){
					els.image.hide();
					els.loading.hide();
					currentImage.src = images[activeImage][0];
					
	            }).createDelegate(this);
				
				if(images.length !== 0){
	            	preload.src = images[activeImage][0];
				}
				else{
					alert('DB error: image does not exist.');
				}
			
        },

        resizeImage: function(w, h){
            var wCur = els.outerImageContainer.getWidth();
            var hCur = els.outerImageContainer.getHeight();

            var wNew = (w + this.borderSize * 2);
            var hNew = (h + this.borderSize * 2);
			this.imageHeight = 630;
			//SET TOP PADDING (VERTICAL CENTER IMAGE)
			var imageResize = 477-h;
			if(imageResize > 0) {
				
				var paddingTop = Math.round(imageResize / 2)+'px;';
				var heightEl = 484 - (Math.round(imageResize / 2)) +'px;';
				
				els.imageDiv.applyStyles('padding-top: '+paddingTop);
				els.imageDiv.applyStyles('height: '+heightEl);
				//els.outerImageContainer.applyStyles('height: 630px');
				els.descriptionLinks.setStyle('top', '50px');
				els.description.applyStyles('top: 554px');
			}
			else{
				els.imageDiv.applyStyles('padding-top: 32px');
				var heightEl = h + 37 +'px;';
				var heightAll = h + 162 + 52 +'px;';
				this.imageHeight = h + 162 + 52;
				var heightDecs = h + 84 + 57 +'px;';
				els.imageDiv.applyStyles('height: '+heightEl);
				
				//els.outerImageContainer.applyStyles('height: '+ heightAll);
				els.description.applyStyles('top: '+ heightDecs);
			}
			
			var timeout = (Ext.isGecko3) ? 100 : 250;
            (function(){
				els.hoverNav.setWidth(els.imageContainer.getWidth() + 'px');
                this.showImage();
            }).createDelegate(this).defer(timeout);
        },

        showImage: function(){

			els.image.show();
			this.updateDetails();
          	this.preloadImages();
			
        },

        updateDetails: function(){
			//get image id 
			var objektId = images[activeImage][1];
			var firstObjektHref = images[0][0];
			
			//get object id (images from ajax)
			if(oneObjectImages == true) {
				objektId = selectedImage.id;
			}
			
			var imageIdArr = objektId.split("-");
			var objektTypeId = imageIdArr[imageIdArr.length-2];
			var imageId = imageIdArr[imageIdArr.length-1];
			
			
			if(Ext.get('image-title-'+imageId) !== null){
				var imagedescHeader = Ext.get('image-title-'+imageId).dom.innerHTML;
				els.descriptionHeader.update(imagedescHeader);
			}
			else {
				els.descriptionHeader.update('');
			}
			
			if(Ext.get('image-desc-'+imageId) !== null){
				var imagedescInfo = Ext.get('image-desc-'+imageId).dom.innerHTML;
				els.descriptionInfo.update(imagedescInfo);
			}
			else {
				els.descriptionInfo.update('');
			}
			
			if(Ext.get('image-detailsObject-'+imageId) !== null){
				var imagelinkToObject = Ext.get('image-detailsObject-'+imageId).dom.href;
				els.linkObject.dom.href = imagelinkToObject;
			}
			else {
				els.linkObject.dom.style.display = 'none';
			}
			
			
			//Villa and Hotel update description.
			if(oneObjectImages == true) {
				if(images[activeImage][2] !== undefined && images[activeImage][2] !== ''){
					els.descriptionHeaderDiv.setStyle('height', 'auto');
					//els.outerImageContainer.setStyle('height', '630px');
					els.outerImageContainer.setStyle('height', this.imageHeight+'px');
					els.descriptionHeaderText.update('&nbsp;- '+images[activeImage][2]);
				}
			}
			else if(Ext.get('objekt-text-'+imageId) !== null){
				var objektText = Ext.get('objekt-text-'+imageId).dom.innerHTML;
				objektText = objektText.replace(/<br(.){0,3}>/ig,"&nbsp;&nbsp; ");
				
				els.descriptionHeaderText.update('&nbsp;- '+objektText);
				var headerTextHeight = els.descriptionHeaderText.getHeight();

				if(headerTextHeight >= 30){
					//els.outerImageContainer.setStyle('height', '645px');
					els.outerImageContainer.setStyle('height', this.imageHeight+'px');
					
					//els.descriptionLinks.setStyle('top', '65px');
					els.descriptionHeaderDiv.setStyle('height', '30px');
					els.descriptionHeaderDiv.setStyle('overflow', 'hidden');
					
					this.cutDescriptionHeaderText(els.descriptionHeaderText,30);
					
				}
				else{
					//els.outerImageContainer.setStyle('height', '630px');
					els.outerImageContainer.setStyle('height', this.imageHeight+'px');
					els.descriptionHeaderDiv.setStyle('height', 'auto');
				}
			}
			else {
				els.descriptionHeaderText.update('');
				//els.outerImageContainer.setStyle('height', '630px');
				els.outerImageContainer.setStyle('height', this.imageHeight+'px');
				els.descriptionHeaderDiv.setStyle('height', 'auto');
			}
			
			
			
			
			//Close wishlist popup when reload image
			if(otherPopupToClose !== '' && this.clickWishlistLink == false){
				otherPopupToClose.closePanel();
			}
			this.clickWishlistLink = false;
			//console.log(objektTypeId+'-'+imageId+' ----- '+firstObjektHref);
			
			els.linkBackToList.set({id: 'linkBackToList-'+objektTypeId+'-'+imageId});
			els.linkBackToList.set({href: firstObjektHref});
			
			
			//set add to wishlist button onclick event
			if(Ext.get('wishList_'+objektTypeId+'_'+imageId) !== null){
				var elWishlist = Ext.get('wishList_'+objektTypeId+'_'+imageId);
				
				var elOnClickEv = elWishlist.getAttribute('onclick');
				var elImageClass = Ext.get('wishList_'+objektTypeId+'_'+imageId+'_img').dom.className;
				var slideshowWishListID = 'slideshowWishList_'+objektTypeId+'_'+imageId;
				var slideshowWishListImgID = slideshowWishListID+'_imgBlank';
				
				els.linkWishlist.set({id: slideshowWishListID});
				els.linkWishlistImg.set({id: slideshowWishListImgID});
				els.linkWishlist.update(elWishlist.dom.innerHTML);
				els.linkWishlistImg.dom.className = elImageClass;
				els.linkWishlist.dom.onclick = elWishlist.dom.onclick;
				
				
				//Update wishlist panel login and register hidden fields.
				if(Ext.get('wl_wishlistData_login') !== null){
					Ext.get('wl_wishlistData_login').dom.value = objektTypeId +','+imageId;
				}
				if(Ext.get('wl_wishlistData_register') !== null){
					Ext.get('wl_wishlistData_register').dom.value = objektTypeId +','+imageId;
				}
				
				
				/*els.linkWishlist.on('click', function(ev,t){
					elWishlist.on();
					console.log('test');
					
				});*/
				
				
				wisthListForm.setSecWistListItemToUpdate(elWishlist.id);
				
				els.linkWishlist.on('click', function(ev) {
					if(this.playing || this.autoPlayFlag) {
						this.clickWishlistLink = true;
						this.pause();
					}
	            }, this);
			}
			
			
			//wishList_7_476
			//Config bottom links 
		
			if(slideType == 'ajaxObjektImages' || slideType == 'objektDetails' || slideType == 'none'){
				els.linkPictures.dom.style.display = 'none';
			}
			else{
				els.linkPictures.dom.style.display = 'inline';
			}
			
			if(slideType == 'all' || slideType == 'objektDetails' || slideType == 'none'){
				els.linkBackToList.dom.style.display = 'none';
			}
			else{
				els.linkBackToList.dom.style.display = 'inline';
			}
			
			if(slideType == 'objektDetails' || slideType == 'none'){
				els.linkObject.dom.style.display = 'none';
			}
			else{
				els.linkObject.dom.style.display = 'inline';
			}
			
			if(slideType == 'objektDetails' || slideType == 'none'){
				els.linkWishlist.dom.style.display = 'none';
			}
			else{
				els.linkWishlist.dom.style.display = 'inline';
			}

		
			var viewSize = this.getViewSize();

			if(Ext.isIE6){
            	els.overlay.setHeight(viewSize[1] + 'px');
			}
            this.updateNav();
			
        },

        updateNav: function(){
            this.enableKeyNav();

            els.hoverNav.show();
			//els.navPlayPause.show();
			

            // if not first image in set, display prev image button
            //if (activeImage > 0)
			if(images.length !== 1)
               	els.navPrev.show();

            // if not last image in set, display next image button
			//   if (activeImage < (images.length - 1))
            if (activeImage < images.length && images.length !== 1)
                els.navNext.show();
        },

        enableKeyNav: function() {
            Ext.fly(document).on('keydown', this.keyNavAction, this);
        },

        disableKeyNav: function() {
            Ext.fly(document).un('keydown', this.keyNavAction, this);
        },

        keyNavAction: function(ev) {
            var keyCode = ev.getKey();

            if (
                //keyCode == 88 || // x
                //keyCode == 67 || // c
                keyCode == 27
            ) {
                this.close();
            }
           /* else if (keyCode == 80 || keyCode == 37){ // display previous image
                if (activeImage != 0){
                    this.setImage(activeImage - 1);
                }
            }
            else if (keyCode == 78 || keyCode == 39){ // display next image
                if (activeImage != (images.length - 1)){
                    this.setImage(activeImage + 1);
                }
            }*/
        },

        preloadImages: function(){
            var next, prev;
            if (images.length > activeImage + 1) {
                next = new Image();
                next.src = images[activeImage + 1][0];
            }
            if (activeImage > 0) {
                prev = new Image();
                prev.src = images[activeImage - 1][0];
            }
        },

        close: function(){
			
			//Auto play
			this.pause();
			els.image.hide();
			if(otherPopupToClose !== ''){
				otherPopupToClose.closePanel();
			}
					
            this.disableKeyNav();
            els.lightbox.hide();
            els.overlay.fadeOut({
                duration: this.overlayDuration
            });
            els.shim.hide();
            this.fireEvent('close', activeImage);
        },

        getViewSize: function() {        
            return [Ext.lib.Dom.getViewWidth(), Ext.get('page').getHeight()];
			//return [Ext.lib.Dom.getViewWidth(), Ext.lib.Dom.getViewHeight()];
        },
		
		registerLog: function(logValAt){
			this.logVal = logValAt;
		},
		cutDescriptionHeaderText: function(descriptionHeaderTextAt, height){
			//els.descriptionHeaderText.getHeight();
			while(descriptionHeaderTextAt.getHeight() > height){
				var descriptionHeaderTextArr = descriptionHeaderTextAt.dom.innerHTML.split("...");
				var text = descriptionHeaderTextArr[0];
				var objektLink = descriptionHeaderTextArr[1];
				
				//alert(objektLink + ' :::::: '+text);
				
				if(objektLink == undefined){
					objektLink = '';
				}
				else if(objektLink.search("[^.]") == 1){
					objektLink = objektLink.substr(1,objektLink.length);
				}
				
				var lastSpace = text.lastIndexOf(" ");
				var textWithotLastSpace = text.substr(0,lastSpace);
				descriptionHeaderTextAt.dom.innerHTML = textWithotLastSpace + "..." + objektLink;
			}
        }
    }
})();

Ext.onReady(Ext.ux.Lightbox.init, Ext.ux.Lightbox);/*
Sardegna2
SlidePanels JS
 
All material herein (c) Copyright 2009 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Rob
 
Changes (incl. date and name)
8/27/09 Luk: created
 
Purpose and Notes:
Required Parameters:
Optional Parameters:
Returns:


--- Login and User Panels


Class: SlidePanels

Method:
	init
	slidePanelEvents
	animationPanel
	showWishListPanel
*/

SlidePanels = function() {
	
};

SlidePanels.prototype = {
	transitionDuration: '1'
	,showslidePanelShim: false
	,init: function(id,slideDiractionAt,opacity){
		this.showClass = 'show-'+id+'-slidepanel';
		this.idButton = 'panel_button_'+id;
		this.idEl = 'slide_panel_'+id;
		this.formId = id+'_form';
		this.opacity = opacity;
		this.opacityVal = '.'+opacity;
		this.idCloseButton = 'close_panel_'+id;
		this.slideDiraction = slideDiractionAt;
		this.thisExtEl = 'none';
		this.alignToButton = '';
		this.shiftPositionArr = '';
		this.buttonsClass = '';
		this.getContentFormEl = '';
		this.getContent = false;
		this.nextHiddenField = '';
		this.slidePanelOverlayDuration = 0.2;
		this.slidePanelOverlayOpacity = 0.3;
		
		/*this.getContentContainerID = '';
		this.getContentFormId = '';
		this.getContentFileUrl = '';
		this.loaderEl = '';*/
	}
	,slidePanelEvents:function(){

		if(Ext.get(this.idCloseButton) !== null){
			Ext.get(this.idCloseButton).on('click', function(e, t) {
				var action = 'hidde';
				this.animationPanel(action);
			}, this);
		}
		
		
		if(Ext.get(this.idButton) !== null){
			Ext.get(this.idButton).on('click', function(e, t) {
				
				if(this.shiftPositionArr !== ''){
					var shiftPositionArrVar = this.shiftPositionArr;
				}
				else{
					var shiftPositionArrVar = [0,0];
				}
				
				//align panel to button
				if(this.alignToButton !== ''){
					this.setPanelLocation(Ext.get(this.idButton), this.alignToButton, shiftPositionArrVar);
				}
				
				this.animationPanel();
			}, this);
		}

	}
	,homeGlobalEvent:function(){
		 Ext.fly(document).on('click', function(ev){
		 	 var target = ev.getTarget('#slide_panel_user');
			 	//console.log(target);
			 if(target == null){
				this.animationPanel('hidde');
			 }
		 
		 }, this);
	}
	,setPanelPositionToButton: function(alignToButtonAt, shiftArrAt){
		this.alignToButton = alignToButtonAt;	
		
		if(shiftArrAt !== undefined){
			this.shiftPositionArr = shiftArrAt;
		}
	}
	,setPanelButtonsClass: function(buttonsClassAt){
		this.buttonsClass = buttonsClassAt;
	}
	,animationPanel:function(actionAt, elementAt){
		
		if(this.opacity !== undefined){
			Ext.get(this.formId).setOpacity(this.opacityVal);
		}
	
		if(actionAt == undefined || actionAt == ''){
			if(Ext.get(this.idEl).hasClass(this.showClass) == true){
				var action = 'hidde';
			}
			else{
				var action = 'show';
			}
		}
		
		//animation
		Ext.get(this.idEl).stopFx(false);
		if(action == 'show'){
			if(this.showslidePanelShim){
				this.showSlidePanelShimFunction();
			}
			
			Ext.get(this.idEl).setStyle("display", "block");
			
			if(this.getContent == true){
				eval(this.getContentFormEl+'.getContentRequest()');
			}	
			
			Ext.get(this.idEl).slideIn(this.slideDiraction, { duration: this.transitionDuration });
			Ext.get(this.idEl).addClass(this.showClass);
			if(Ext.get(this.idButton) !== null){
				Ext.get(this.idButton).addClass('open');
			}
			else if(elementAt !== undefined){
				elementAt.addClass('open');
			}
		}
		else {
			if(Ext.get(this.idEl).hasClass(this.showClass) == true){
				Ext.get(this.idEl).slideOut(this.slideDiraction, { duration: this.transitionDuration });
			}
			Ext.get(this.idEl).removeClass(this.showClass);
			if(Ext.get(this.idButton) !== null){
				Ext.get(this.idButton).removeClass('open');
			}
			else if(elementAt !== undefined){
				elementAt.removeClass('open');
			}
			//wishlist click close icon
			else if(this.thisExtEl !== undefined && this.thisExtEl !== 'none'){
				this.thisExtEl.removeClass('open');
			}
			if(this.showslidePanelShim){
				this.hiddeSlidePanelShimFunction();
			}
		}
		
	}
	,setNextHiddenField: function(idHiddenField){
		if(idHiddenField !== undefined){
			this.nextHiddenField = Ext.get(idHiddenField);
		}
	}
	//showSlidePanel   showWishListPanel
	,showSlidePanel: function(thisEl,idHiddenField){
		this.thisExtEl = Ext.get(thisEl.id);
		var hiddenField = Ext.get(idHiddenField);
		//var buttonHeight = 22; 
		
		//Set opacity panel
		if(this.opacity !== undefined){
			Ext.get(this.formId).setOpacity(this.opacityVal);
		};
		
		if(this.alignToButton !== ''){
			var alignToButtonVar = this.alignToButton;
		}
		else{
			var alignToButtonVar = 'lb';
		}
		
		if(this.shiftPositionArr !== ''){
			var shiftPositionArrVar = this.shiftPositionArr;
		}
		else{
			var shiftPositionArrVar = [0,0];
		}
		
		if(idHiddenField !== undefined){
			var idArr = thisEl.id.split("_");
			var elType = idArr[0];
			var idTables = idArr[1];
			var idObject = idArr[2];
			
			if(elType == 'slideshowWishList' || this.showslidePanelShim){
				Ext.get(this.idEl).set({style: 'z-index: 20000;'});
			}
			else{
				Ext.get(this.idEl).set({style: 'z-index: 900;'});
			}
			
			var hiddenFieldValueArr = hiddenField.getValue().split(",");
			
			//Set hidden value id_tables,objectID
			hiddenField.set({value: idTables+','+idObject});
						
			if(hiddenFieldValueArr.length == 2){
				if(idTables == hiddenFieldValueArr[0] && idObject == hiddenFieldValueArr[1]){
					
					this.setPanelLocation(this.thisExtEl, alignToButtonVar, shiftPositionArrVar);
					//animate panel close
					this.animationPanel('', this.thisExtEl);
				}
				else{
					if(Ext.get(this.idEl).hasClass(this.showClass) == false){
						//Set popup position
						this.setPanelLocation(this.thisExtEl, alignToButtonVar, shiftPositionArrVar);
						//animate panel
						this.animationPanel('', this.thisExtEl);
					}
					else{
						this.resetAllButtonsState();
						
						//getcontent
						if(this.getContent == true){
							eval(this.getContentFormEl+'.getContentRequest()');
						}
						
						//Set popup position
						this.setPanelLocation(this.thisExtEl, alignToButtonVar, shiftPositionArrVar, true);
					}
				}
			}
			else{
				//first open
				//Set popup position
				this.setPanelLocation(this.thisExtEl, alignToButtonVar, shiftPositionArrVar);
				//animate panel
				this.animationPanel('', this.thisExtEl);
			}
			//Set hidden value id_tables,objectID
			//hiddenField.set({value: idTables+','+idObject});
			
			if(this.nextHiddenField !== ''){
				this.nextHiddenField.set({value: idTables+','+idObject});
			}
		}
		else{
			//Set popup position
			this.setPanelLocation(this.thisExtEl, alignToButtonVar, shiftPositionArrVar);
			//animate panel
			this.animationPanel('', this.thisExtEl);
		}
	}
	,setPanelLocation: function(elAt, alignAt, shiftArr, animAt){
		var shiftX = shiftArr[0];
		var shiftY = shiftArr[1];
		var elX = elAt.getX();
		var elY = elAt.getY();
		
		
		
		if(alignAt.search('r') !== -1){
			shiftX = (shiftX + elAt.getWidth());	
		}
		if(alignAt.search('b') !== -1){
			shiftY = (shiftY + elAt.getHeight());
		}
		
		// center X to defined container
		if(alignAt.search('c') == 0){
			if (isNaN(Number(shiftX))){
				var alignElement = Ext.get(shiftX);
				if(alignElement !== undefined){
					var alignToElementWidth = alignElement.getWidth();
					var panelWidth = Ext.get(this.idEl).getWidth();
					elX = alignElement.getX() + (alignToElementWidth-panelWidth)/2 ;
				}
			}	
		}
		
		// center Y to defined container
		if(alignAt.search(/c$/g) == 1){
			if (isNaN(Number(shiftY))){
				var alignElement = Ext.get(shiftY);
				if(alignElement !== undefined){
					var alignToElementHeight = alignElement.getHeight();
					var panelHeight = Ext.get(this.idEl).getHeight();
					elY = alignElement.getY() + (alignToElementHeight-panelHeight)/2 ;
				}
			}	
		}
		
		//console.log(shiftX +' - '+ shiftY+' ---- '+Ext.get(this.idButton).getHeight());
		if(shiftX !== 0 && !isNaN(Number(shiftX))){
			positionX = elX+shiftX;
		}
		else{
			positionX = elX;
		}
		
		if(shiftY !== 0 && !isNaN(Number(shiftY))){
			positionY = elY+shiftY;
		}
		else{
			positionY = elY;
		}
		
		if(animAt == undefined){
			animAt = false; 
		}
		
		Ext.get(this.idEl).setLocation(positionX,positionY,animAt);
	}
	,resetAllButtonsState: function(){
		//var buttonsList = Ext.select('.wishListButton');
		if(this.buttonsClass !== undefined && this.buttonsClass !== ''){
			var buttonsList = Ext.select('.'+this.buttonsClass);
			
			for(i=0; i < buttonsList.getCount(); i++){
				var item = buttonsList.item(i);
				item.removeClass('open');
			}
			this.thisExtEl.addClass('open');
		}
		
	}
	,closePanel: function(){
		var action = 'hidde';
		this.animationPanel(action);
	}
	,setPanelGetContentForm: function(getContentFormEl){
		this.getContentFormEl = getContentFormEl;
		this.getContent = true;
	}
	,showSlidePanelShim: function(){
		this.showslidePanelShim = true;
		this.showSlidePanelShimMarkup();
	}
	,showSlidePanelShimMarkup: function(){
		 this.slidePanelShim = Ext.DomHelper.append(document.body, {
             tag: 'iframe',
             id: 'ux-slidePanel-shim'
         }, true);
         this.slidePanelOverlay = Ext.DomHelper.append(document.body, {
             id: 'ux-slidePanel-overlay'
         }, true);
		 Ext.each([this.slidePanelOverlay, this.slidePanelShim], function(el){
             el.setVisibilityMode(Ext.Element.DISPLAY)
             el.hide();
         });
		 this.slidePanelOverlay.on('click', this.closePanel, this);
	}
	,showSlidePanelShimFunction: function(){
		var viewSize = this.getViewSize();
		this.slidePanelShim.setStyle({
        	width: viewSize[0] + 'px',
        	height: viewSize[1] + 'px'
        }).show();
		this.slidePanelOverlay.fadeIn({
            duration: this.slidePanelOverlayDuration,
            endOpacity: this.slidePanelOverlayOpacity,
            scope: this
        });
	}
	,hiddeSlidePanelShimFunction: function(){
		this.slidePanelShim.hide();
		 this.slidePanelOverlay.fadeOut({
         	duration: this.slidePanelOverlayDuration
         });
	}
	,getViewSize: function() {        
            return [Ext.lib.Dom.getViewWidth(), Ext.get('page').getHeight()];
			//return [Ext.lib.Dom.getViewWidth(), Ext.lib.Dom.getViewHeight()];
    }
	/*,setPanelGetContent: function(getContentContainerID, getContentFormId, getContentFileUrl, loaderIdAt){
		this.getContent = true;
		this.getContentContainerID = getContentContainerID;
		this.getContentFormId = getContentFormId;
		this.getContentFileUrl = getContentFileUrl;
		
		if(loaderIdAt !== undefined){
			this.loaderEl = Ext.get(loaderIdAt);
		}
		
	}
	,getContentRequest: function(){
		
		if(this.loaderEl !== null){
			this.loaderEl.dom.style.display = 'block';
		}
	
		Ext.Ajax.request({
		    form: this.getContentFormId,
			url: this.getContentFileUrl,
			success: function(response, opts) {
		      var responseObj = Ext.decode(response.responseText);
			  this.loaderEl.dom.style.display = 'none';
			  
			  Ext.get(this.getContentContainerID).update(responseObj.content);
			 
			  if(responseObj.nextRequest !== "" || responseObj.nextRequest !== false){
				eval('this.'+responseObj.nextRequest+'("'+responseObj.date+'")');
			  }
			  
			 
			  //this.responseRequest(responseObj);
		      //console.dir(obj);
		   },
		   failure: function(response, opts) {
		      console.log('server-side failure with status code ' + response.status);
		   },
		   scope: this
		});
	}
	,setPrevNextEvents: function(prevButtonClass, nextButtonClass){
		
		if(prevButtonClass !== undefined){
			Ext.select('.'+prevButtonClass).on('click', function(e, t) {
				var targetIdArr = t.id.split('_');
				var date = targetIdArr[targetIdArr.length - 1];
				Ext.get('dateToCheck').set({value: "{d '"+date+"'}"});
				this.getContentRequest();
			}, this);
		}
		
		if(nextButtonClass !== undefined){
			Ext.select('.'+nextButtonClass).on('click', function(e, t) {
				var targetIdArr = t.id.split('_');
				var date = targetIdArr[targetIdArr.length - 1];
				Ext.get('dateToCheck').set({value: "{d '"+date+"'}"});
				this.getContentRequest();
			}, this);
		}
	
		
	}
	,updateVillaAvailabilityFields: function(date){
		//update date field after request
		Ext.get('dateToCheck').set({value: date});
		//set prev and next buttons events
		this.setPrevNextEvents('villaAv_prevButton', 'villaAv_nextButton');
	}*/

};
/*
Sardegna2
RightTabs JS
 
All material herein (c) Copyright 2009 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Rob
 
Changes (incl. date and name)
8/27/09 Luk: created
 
Purpose and Notes:
Required Parameters:
Optional Parameters:
Returns:

Class: RightTabs

Method:
	init
	changeTab('element')
	selectTab('villa or hotel')
	initVillaSelects
	initHotelSelects
	

*/

var selected = '';

RightTabs = {
	init:function(){
	
		if(selected == '')
			RightTabs.selectTab('villa');
		
		
		Ext.select('.rightTabs').on('click', function(e, t) {
		   //alert(t.id);
		   RightTabs.changeTab(t);

		}, null, {delegate: 'li'});
	}
	,changeTab:function(t){
		Ext.get(t.id).radioClass('tab-show');
    	Ext.get('content' + t.id.slice(-1)).radioClass('tab-content-show');
	   
		if(t.id == 'tab2'){
			SlideSearchPanel.changePanel('Hotel');
			
			//create comboBox Hotel
			RightTabs.initHotelSelects();

		}
		else{
			//create comboBox Villa
			RightTabs.initVillaSelects();
			SlideSearchPanel.changePanel('Villa');
		}
	}
	,selectTab:function(tab){
		selected = tab;
		rightTabWebsiteForm = new WebsiteForm();
		if(tab !== undefined){
			if(tab == 'hotel') {
				tabEl = document.getElementById('tab2');
				rightTabWebsiteForm.radioSearchByNameChange('hotels');
				
			}
			else{
				tabEl = document.getElementById('tab1');
				rightTabWebsiteForm.radioSearchByNameChange('villas');
			}
		}
		
		if(tabEl !== null)
			RightTabs.changeTab(tabEl);
	}
	,initVillaSelects:function(){
		//create comboBox Villa
		if(Ext.get('travelingPersons').getAttribute('type') !== "hidden"){
			var convertedTravelingPersons = new Ext.form.SardinienComboBox({transform:'travelingPersons', width:152});
			var convertedBathrooms = new Ext.form.SardinienComboBox({transform:'bathrooms', width:152});
			var convertedPriceClass = new Ext.form.SardinienComboBox({transform:'priceClass', width:152});
			//var converted = new Ext.form.SardinienComboBox({transform:'regionID', width:152});
			var convertedDistanceToSea = new Ext.form.SardinienComboBox({transform:'distanceToSea', width:152});
			
			//reset form: onclick New Search
			RightTabs.resetSelectValue([convertedTravelingPersons,convertedBathrooms,convertedPriceClass,convertedDistanceToSea]);
		}
	}
	,initHotelSelects:function(){
		//create comboBox Hotel
		if(Ext.get('hotelStars').getAttribute('type') !== "hidden"){
			var convertedHotelStars = new Ext.form.SardinienComboBox({transform:'hotelStars', width:152});
			var convertedHotelRegion = new Ext.form.SardinienComboBox({transform:'hotelRegion', width:152});
			var convertedHotelBeach = new Ext.form.SardinienComboBox({transform:'hotelBeach', width:152});
			
			//reset form: onclick New Search
			RightTabs.resetSelectValue([convertedHotelStars,convertedHotelRegion,convertedHotelBeach]);
		}
	}
	,resetSelectValue: function(elementArr){
		
		Ext.select('.linkNewSearch').on('click', function(e, t) {
			for(i=0; i < elementArr.length; i++){
				var item = elementArr[i];

				if(item.hiddenName == 'hotelStars'){
					var firstVal = item.store.data.items[1].data.value;
				}
				else{
					var firstVal = item.store.data.items[0].data.value;
				}
				
				item.setValue(firstVal);
			}
			Ext.get('pool').dom.checked = false;
		});
	}
};/*
Sardegna2
SlideSearchPanel JS
 
All material herein (c) Copyright 2009 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Rob
 
Changes (incl. date and name)
8/27/09 Luk: created
 
Purpose and Notes:
Required Parameters:
Optional Parameters:
Returns:


--- inc_rightPanel.cfm  Right advance search panel


Class: SlideSearchPanel

Method:
	searchPanelEvents
	showVillaPanel
	showHotelPanel
	showPanel
	hiddePanel
	changePanel
	transformHotelSelects
	transformVillaSelects
	getShowPosition
	getHiddePosition
	animationPanel
	setPanelFieldToForm(type, element, formElement)
*/

/*
transitionEasing: (effects list)
    * backBoth
    * backIn
    * backOut
    * bounceBoth
    * bounceIn
    * bounceOut
    * easeBoth
    * easeBothStrong
    * easeIn
    * easeInStrong
    * easeNone
    * easeOut
    * easeOutStrong
    * elasticBoth
    * elasticIn
    * elasticOut
*/

SlideSearchPanel = {
	idEl: 'slideSearchPanel'
	,idContainer: 'slideSearchPanelContainer'
	,idVillaButton: 'searchPanelButtonVilla'
	,idHotelButton: 'searchPanelButtonHotel'
	,idHotelClose: 'slideSearchPanelCloseHotel'
	,idVillaClose: 'slideSearchPanelCloseVilla'
	,offset: '636'
	,transitionDuration: '1'
	,transitionEasing: 'easeOut'
	,searchPanelEvents:function(){
		//alert('ok');
		this.villaButtonRefine = Ext.select('.searchPanelButtonVillaRefine');
		this.hotelButtonRefine = Ext.select('.searchPanelButtonHotelRefine');
		
		//Show Villa Advanced Search Panel
		Ext.get(this.idVillaButton).on('click', function(e, t) {
			this.showVillaPanel();
		},this);
		
		//show Hotel Advanced Search Panel
		Ext.get(this.idHotelButton).on('click', function(e, t) {
			this.showHotelPanel();
		},this);
		

		//-Refine Buttons
		if(this.villaButtonRefine.getCount !== 0){
			//Show Villa Advanced Search Panel
			this.villaButtonRefine.on('click', function(e, t) {
				this.showVillaPanel('refine_btn');
			},this);
		}
		
		if(this.hotelButtonRefine.getCount !== 0){
			//Show Villa Advanced Search Panel
			this.hotelButtonRefine.on('click', function(e, t) {
				this.showHotelPanel('refine_btn');
			},this);
		}
		//---------------
		
		//Close Villa Advanced Search Panel
		Ext.get(this.idVillaClose).on('click', function(e, t) {
			SlideSearchPanel.hiddePanel();
		});
		
		
		//Close Hotel Advanced Search Panel
		Ext.get(this.idHotelClose).on('click', function(e, t) {
			SlideSearchPanel.hiddePanel();
		});
	}
	,onloadStartSearchVilla:function(){
		this.showVillaPanel('onloadEvent');
	}
	,onloadStartSearchHotel:function(){
		this.showHotelPanel('onloadEvent');
	}
	,showVillaPanel:function(fromEv){
		//select villa tab 
		if(fromEv !== undefined && (fromEv == 'refine_btn' || fromEv == 'onloadEvent')){
			RightTabs.selectTab('villa');
		}
		this.idButton = this.idVillaButton;
		Ext.get('searchVillasPanel').setDisplayed(true);
		Ext.get('searchHotelsPanel').setDisplayed(false);
		SlideSearchPanel.showPanel(fromEv);
			
		SlideSearchPanel.transformVillaSelects();
	}
	,showHotelPanel:function(fromEv){
		//select hotel tab 
		if(fromEv !== undefined && (fromEv == 'refine_btn' || fromEv == 'onloadEvent')){
			RightTabs.selectTab('hotel');
		}
		
		this.idButton = this.idHotelButton;
		Ext.get('searchVillasPanel').setDisplayed(false);
		Ext.get('searchHotelsPanel').setDisplayed(true);
		SlideSearchPanel.showPanel(fromEv);
			
		SlideSearchPanel.transformHotelSelects();
	}
	,showPanel:function(fromEv){
		//alert('ok80');
		var showPanel = Ext.get('slideSearchPanel').hasClass('show-slide-panel');
		
		/*if(fromEv !== undefined && fromEv == 'refine_btn' && showPanel == true){
			//don't hidde if clicked refine button
		}
		else{*/
			//show / hidde panel
			Ext.get('slideSearchPanelContainer').addClass('showSlideSearchPanelContainer');
			if(showPanel == true){
				var xNew = SlideSearchPanel.getHiddePosition();
				var action = 'hidde';
			}
			else{
				var xNew = SlideSearchPanel.getShowPosition();
				var action = 'show';
			}
			SlideSearchPanel.animationPanel(xNew, action, fromEv);
		/*}*/
	}
	,hiddePanel:function(){
		//alert('ok90');
		var xNew = SlideSearchPanel.getHiddePosition();
		var action = 'hidde';
		SlideSearchPanel.animationPanel(xNew, action);
	}
	//tabs
	,changePanel:function(panelType){
		if(panelType == 'Hotel'){
			Ext.get('searchVillasPanel').setDisplayed(false);
			Ext.get('searchHotelsPanel').setDisplayed(true);
			SlideSearchPanel.transformHotelSelects();
		}
		else{
			Ext.get('searchVillasPanel').setDisplayed(true);
			Ext.get('searchHotelsPanel').setDisplayed(false);
			SlideSearchPanel.transformVillaSelects();
		}
		
	}
	,transformHotelSelects:function(){
		if(Ext.get('hotelSizeForm').getAttribute('type') !== "hidden"){
			convertedHotelSize = new Ext.form.SardinienComboBox({transform:'hotelSizeForm', width:152});
			
			//Hotels Slide Panel Fields Initialization
			SlideSearchPanel.setPanelFieldToForm('class', '.hotelBoardFields', 'hotelBoard');
			SlideSearchPanel.setPanelFieldToForm('select', 'convertedHotelSize', 'hotelSize');
			SlideSearchPanel.setPanelFieldToForm('class', '.hotelFeatureFields', 'hotelFeatures');
		}
	}
	,transformVillaSelects:function(){
		if(Ext.get('villaBedrooms').getAttribute('type') !== "hidden"){
			convertedVillaBedrooms = new Ext.form.SardinienComboBox({transform:'villaBedrooms', width:192});
			
			//Villas Slide Panel Fields Initialization
			SlideSearchPanel.setPanelFieldToForm('select','convertedVillaBedrooms', 'bedrooms');
			SlideSearchPanel.setPanelFieldToForm('class','.regionFields', 'regionID');
			SlideSearchPanel.setPanelFieldToForm('class','.villaFeatureFields', 'villaFeatures');
		}

	}
	,getShowPosition:function(){
		var xNew = (-1 * this.offset) + Ext.get(this.idEl).getX();
		Ext.get(this.idEl).addClass('show-slide-panel');
		//Ext.get(this.idContainer).addClass('container-show');
		
		return xNew;
	}
	,getHiddePosition:function(){
		var xNew = (1 * this.offset) + Ext.get(this.idEl).getX();
		Ext.get(this.idEl).removeClass('show-slide-panel');
		
		
		return xNew;
	}
	,animationPanel:function(xNew,action, fromEv){
		
		Ext.get(this.idVillaButton).removeAllListeners();
		Ext.get(this.idHotelButton).removeAllListeners();
		
		if(this.villaButtonRefine !== undefined && this.villaButtonRefine.getCount !== 0)
			this.villaButtonRefine.removeAllListeners();
			
		if(this.hotelButtonRefine !== undefined && this.hotelButtonRefine.getCount !== 0)
			this.hotelButtonRefine.removeAllListeners();
		
		Ext.get(this.idHotelClose).removeAllListeners();
		Ext.get(this.idVillaClose).removeAllListeners();

		//animation
		Ext.get(this.idEl).stopFx(false);
		Ext.get(this.idEl).shift({
			duration: this.transitionDuration
			,x: xNew
			,easing: this.transitionEasing
			,callback: function(){
				
				if(fromEv == undefined || fromEv !== 'onloadEvent'){
					SlideSearchPanel.searchPanelEvents();
				}
				
				//hidde slide conteiner
				if(action == 'hidde') {
					Ext.get('slideSearchPanelContainer').removeClass('showSlideSearchPanelContainer');
					
				}
			}
       	});
		
	}
	,setPanelFieldToForm:function(type, element, formElement){
		if(type == 'select') {
			eval(element).on('select', function() {
				fieldValue = eval(element).getValue();
				Ext.get(formElement).dom.value = fieldValue;
				//alert(fieldValue);
			});
			
			//reset form: onclick New Search
			Ext.select('.linkNewSearch').on('click', function(e, t) {
				var firstVal = eval(element).store.data.items[0].data.value;
				eval(element).setValue(firstVal);
				Ext.get(formElement).dom.value = '';
			});
		}
		else{
			Ext.select(element).on('click', function(e, t) {
				fieldsList = Ext.select(element);
				var valueList = '';
				for(i=0; i < fieldsList.getCount(); i++){
					var item = fieldsList.item(i);
					if(item.dom.checked == true){
						valueItem = item.getValue();
						if(valueList == '')
							valueList = valueItem;
						else
							valueList = valueList +','+ valueItem;
					}
				}
				
				Ext.get(formElement).dom.value = valueList;

				//alert(valueList);
			});
			
			//reset form: onclick New Search
			Ext.select('.linkNewSearch').on('click', function(e, t) {
				fieldsList = Ext.select(element);
				for(i=0; i < fieldsList.getCount(); i++){
					var item = fieldsList.item(i);
					item.dom.checked = false;
					
					if(item.hasClass("regionFields") &&  item.dom.type == "radio"){
						item.dom.checked = true;
					}
					
				}
				Ext.get(formElement).dom.value = '';
			});
		}
	}
};

DatePicker = function() {
};

DatePicker.prototype = {
	idEl: ''
	,init:function(idElAt, idButton){
		//create the date picker
		var idEl = idElAt;

		if(Ext.get(idEl+'Div') !== null){
			var myDP = new Ext.DatePicker({
				renderTo: idEl+'Div',
				hidden: true,
				startDay: 1,
				cls: 'onlyDatePicker',
				listeners: {
					'select': {
						fn: function(myDP, date){
							var field = Ext.get(idEl); //get the text field
							field.dom.value = date.format('d.m.Y'); //add the selected date to the field
							myDP.hide(); //hide the date picker
						}
					}
				},
				scope: this				
			});
		}
		else{
			alert('Invalid renderTo div name');
		}
		
		//add listener for button click
		Ext.get(idButton).on('click', function(e, t) {
			this.clickHandler(myDP);
		}, this); 
		
	}
	,clickHandler:function(myDP){
		//show the date picker
		myDP.show();
	}
	/*,selectHandler:function(myDP, date){
		//get the text field
		var field = Ext.get(this.idEl);
		alert(this.idEl);
		//add the selected date to the field
		field.dom.value = date.format('d.m.Y');
		//hide the date picker
		myDP.hide();
	}*/
};/*
Sardegna2
WebsiteForm JS
 
All material herein (c) Copyright 2009 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Rob
 
Changes (incl. date and name)
8/27/09 Luk: created
 
Purpose and Notes:
Required Parameters:
Optional Parameters:
Returns:

Class: WebsiteForm

Method:
	validationField('id element','validation type', 'default Value')
	submitFrom(action, nextStepActionAt, urlFile, idButtonAt, idResponseDivAt)
	onClickSubmitEvent()
	requestAjax()
	responseRequest(response)
	translatorPage()
	addRemoveWishList(this)
	updateWistListItems(id element)
	showForm(idFromToChange, formType)
	showSelectedForm(selected Form)
	updateWistListCounter(add or remove)
	radioChackBoxCombination('inputs class') - radio, checkbox: use in Region section - combination radio - checkbox.
	radioSearchByNameEvents(radioClass)
	radioSearchByNameChange(setFormId)
	inputValidation('element','validation type')
	refreshPage()

*/


WebsiteForm = function(idForm) {
    if(idForm) {
        this.init(idForm);
    }
};

WebsiteForm.prototype = {
	idForm: ''
	,logVal: false
	,divForm: ''
	,formSubmitButton: ''
	,errorClass: 'errField'
	,formFieldList: ''
	,formFieldTypeList: ''
	,urlFile: '/lib/services/service.cfm'
	,getContentContainerID: ''
	,getContentFormId: ''
	,getContentFileUrl: ''
	,loaderEl: ''
	,wishListHiddeObject: ''
	,wishListObjectsNoEl: ''
	,slidePanelEl: ''
	,timeout: 2000
		
	,init: function(idFormAt, divFormAt){
		this.idForm = idFormAt;
		this.logVal = logVal;
		
		if(divFormAt !== undefined) {
			this.divForm = divFormAt;
		}
	}
	,validationField: function(idEl,valTypeAt,defaultValueAt){
		var formEl = Ext.get(idEl);
		var defaultValue = defaultValueAt;
		var valType = valTypeAt;
		
		formEl.on('focus',  function(e, el, o){
			//showHiddeDefaultValue
			this.enableKey();
			if(valType == 'password'){
					//console.log(formEl)
					formEl.setStyle('display', 'none');
					Ext.get(formEl.id+'_hidde').setStyle('display', 'block');
					Ext.get(formEl.id+'_hidde').focus();
					this.disableKey();
				}
			else if(defaultValue !== undefined && formEl.getValue() == defaultValue){
				formEl.dom.value = '';
			}
		}, this);
		
		if(valType == 'password'){
			var formElOn = Ext.get(formEl.id+'_hidde');
			if(formElOn !== null){
				formElOn.on('focus',  function(e, el, o){
					this.enableKey();
				}, this);
			}
		}
		else{
			var formElOn = formEl;
		}
		
		formElOn.on('blur', function(e, el, o){
			//showHiddeDefaultValue
			this.disableKey();
			if(defaultValue !== undefined && formElOn.getValue() == ''){
				if(valType == 'password'){
					formElOn.setStyle('display', 'none');
					formEl.setStyle('display', 'block');
				}
				formEl.dom.value = defaultValue;
			}
			
			//Validation field
			if(valType !== ''){
				var valResult = this.inputValidation(formEl,valType);
				//console.log(' Val: '+valType);
				if(valResult == false){
					//Validation Error - add error class to input
					formElOn.addClass(this.errorClass);
				}
				else{
					//Validation OK - remove error class to input
					formElOn.removeClass(this.errorClass);
				}
			}
		}, this);
		
		 	//13
		
		
		if(this.formFieldList == ''){
			this.formFieldList = idEl;
			this.formFieldTypeList = valType;
		}
		else{
			this.formFieldList = this.formFieldList + ',' + idEl;
			this.formFieldTypeList = this.formFieldTypeList + ',' + valType;
		}
	}
	,submitFrom: function(action, nextStepActionAt, urlFile, idButtonAt, idResponseDivAt){
		this.action = action;
		this.formFieldArr = this.formFieldList.split(',');
		this.formFieldTypeArr = this.formFieldTypeList.split(',');
		
		//Set Action after submit
		if(nextStepActionAt !== undefined){
			this.nextStepAction = nextStepActionAt;
		}	
		else {
			this.nextStepAction = '';
		}
		
		//Set url File
		if(idButtonAt !== undefined){
			this.formSubmitButton = Ext.get(idButtonAt);
		}	
		else {
			this.formSubmitButton = Ext.get(this.idForm + '_button');
		}
		
		//Set response Div
		if(idResponseDivAt !== undefined){
			this.responseDiv = Ext.get(idResponseDivAt);
		}	
		else {
			this.responseDiv = Ext.get(this.idForm + '_msg');
		}
		
		//Set url File
		if(urlFile !== undefined){
			this.urlFile = urlFile;
		}
		
		// Set onClick attribute to return false;
		this.formSubmitButton.set({onclick:'return false;'});
		
		//Button event
		this.formSubmitButton.on('click', this.onClickSubmitEvent, this);
	}
	,onClickSubmitEvent: function(){
		var errorList = '';
		
		if(this.formFieldArr.length == 1 && this.formFieldArr[0] == ''){
			//no validation fields
		}
		else{
		//validation field loop
			for (var i = 0, len = this.formFieldArr.length; i < len; i++){
				var formField = Ext.get(this.formFieldArr[i]);
				
				//valudation function
				valResult = this.inputValidation(formField,this.formFieldTypeArr[i]);
				
				if(valResult == false){
					//Validation Error
					formField.addClass(this.errorClass);
					
					if(errorList == '')
						errorList = this.formFieldArr[i];
					else
						errorList = errorList + ',' + this.formFieldArr[i];
				}
				else{
					//Validation OK - remove error class to input
					formField.removeClass(this.errorClass);
				}	
				
			}
		}
		
		if(errorList == ''){
			//console.log('Submit');
			this.requestAjax();
		}
	}
	,requestAjax: function(){
		//AJAX request
		//alert(this.idForm +' - '+ this.action);
		Ext.Ajax.request({
		    form: this.idForm,
			url: this.urlFile,
			params: {cmd: this.action},
			success: function(response, opts) {
		      var responseObj = Ext.decode(response.responseText);
			  this.responseRequest(responseObj);
		      //console.dir(obj);
		   },
		   failure: function(response, opts) {
		      alert('server-side failure with status code ' + response.status);
		   },
		   scope: this
		});
	}
	,responseRequest: function(response){
		if(this.responseDiv !== null){
			//this.responseDiv.update(response.msg);
			this.responseDiv.dom.innerHTML = response.msg;
		}
		//console.dir(response);
		
		if(response.success == true && (this.action == 'recommendToFriends' || this.action == 'technicalQuestions')){
			this.closePanelWithTimeOut();
		}
		
		if(response.success == true && this.action == 'removeAllFromWishlist'){
			this.closePanelWithTimeOut();
			this.refreshPage();
		}
				
		if(response.success == true){
			if(response.msg == 'Translator'){
				this.translatorPage();
			}
			else if(this.action == 'userLogin' || this.action == 'userLogout' || this.action == 'userRegister'){
				if(this.action == 'userLogout'){
					var cookie = new Ext.state.CookieProvider();
					var notLogShowedPanel = cookie.clear('NOTLOGSHOWEDPANEL');
				}
				
				if(this.action == 'userRegister'){
					this.refreshPage(2000);
				}
				else{
					this.refreshPage();
				}
			}
		}
		
		//alert(this.responseDiv);
	}
	,translatorPage: function(){
		alert('Translator has been logged in.\nThe page will be reloaded in order to load translator components.');		
		this.refreshPage();
	}
	,addRemoveWishList: function(thisEl){
		var action = 'addToWislist';
		var idArr = thisEl.id.split("_");
		var idTables = idArr[1];
		var objectID = idArr[2];
		
		//show login panel only first time (not login)
		var cookie = new Ext.state.CookieProvider();
		var notLogShowedPanel = cookie.get('NOTLOGSHOWEDPANEL');

		if(!this.logVal && notLogShowedPanel == undefined){
			if(this.slidePanelEl !== ''){
				this.slidePanelEl.showSlidePanel(thisEl,"wl_wishlistData_login");
				cookie.set('NOTLOGSHOWEDPANEL', 'true');
			}
		}
		
		Ext.Ajax.request({
			url: this.urlFile,
			params: {cmd: action, objektType: idTables, objektID: objectID },
			success: function(response, opts) {
		      var responseObj = Ext.decode(response.responseText);
			  if(responseObj.success == true){
			  	this.updateWistListItems(thisEl.id);				
			  }
			  else{
			  	alert(responseObj.msg)
			  }

			  //this.responseRequest(responseObj);
		      //console.dir(obj);
		   },
		   failure: function(response, opts) {
		      alert('server-side failure with status code ' + response.status);
		   },
		   scope: this
		});
	}
	,setSecWistListItemToUpdate: function(elID){
		this.secWistListItemToUpdate = Ext.get(elID);
	}
	,updateWistListItems: function(thisElID){
		var buttonImg = Ext.get(thisElID+'_img');
		var buttonImgBlank = Ext.get(thisElID+'_imgBlank');
		var thisEl = Ext.get(thisElID);
		var wishListAction = '';
		
		if(this.secWistListItemToUpdate !== undefined){
			buttonImg = Ext.get(this.secWistListItemToUpdate.id+'_img');
			thisEl = this.secWistListItemToUpdate;
		}
		
		//translation variables // footer.cfm
		var addWishListValue = Ext.get('wishList-addToWishList-translation').dom.innerHTML;;
		var removeWishListValue = Ext.get('wishList-removeFromWishList-translation').dom.innerHTML;;
		
		//alert(buttonImg); 
		if(buttonImg !== null) {
			if(buttonImg.hasClass('marken')){
				//add
				buttonImg.replaceClass('marken', 'gemerkt');
				buttonImg.set({src: 'http://files1.sardegna-images.com/layouts/img/checkNote.gif'});
				thisEl.update(removeWishListValue);
				wishListAction = 'add';
			}
			else if(buttonImg.hasClass('gemerkt')){
				//remove
				buttonImg.replaceClass('gemerkt','marken');
				buttonImg.set({src: 'http://files1.sardegna-images.com/layouts/img/note.gif'});
				thisEl.update(addWishListValue);
				wishListAction = 'remove';
			}
		}
		
		thisEl = Ext.get(thisElID);
		
		if(buttonImgBlank !== null) {
			if(buttonImgBlank.hasClass('marken')){
				buttonImgBlank.replaceClass('marken', 'gemerkt');
				thisEl.update(removeWishListValue);
				wishListAction = 'add';
			}
			else if(buttonImgBlank.hasClass('gemerkt')){
				buttonImgBlank.replaceClass('gemerkt','marken');
				thisEl.update(addWishListValue);
				wishListAction = 'remove';
			}
		}
		
		if(wishListAction == 'add'){
			this.updateWistListCounter('add');
		}
		else if(wishListAction == 'remove'){
			this.updateWistListCounter('remove');
		}
		
		//WishList page only
		if(this.wishListObjectsNoEl !== ''){
			var objectsNoElVal = this.wishListObjectsNoEl.dom.innerHTML;
			var objectsNoElValNew  = (objectsNoElVal-1);
			
			this.wishListObjectsNoEl.update(objectsNoElValNew);
			
			if(this.wishListHiddeObject == true){
				var itemDiv = Ext.get(thisElID+'_itemDiv');
				itemDiv.dom.style.display = 'none';
			}
		}
		
	}
	,wishlistPageEvents: function(objectsNoId, hiddeObject){
		if(objectsNoId !== undefined){
			this.wishListObjectsNoEl = Ext.get(objectsNoId);
		}
		
		if(hiddeObject !== undefined){
			this.wishListHiddeObject = hiddeObject;
		}
		
	}
	,showForm: function(idFromToChange, formType){
		var forgotButton = Ext.get(this.idForm+'_'+formType);
		
		// Set onClick attribute to return false;
		forgotButton.set({onclick:'return false;'});
		
		forgotButton.on('click',  function(e, el, o){
			this.showSelectedForm(idFromToChange);
		}, this);
	}
	,showSelectedForm: function(selectedForm){
		
		if(selectedForm == undefined){
			selectedForm = this.idForm;
		}
		//alert(selectedForm);
		
		var formsToChanges = Ext.get(this.divForm).select('form');
			
		for(i=0; i < formsToChanges.getCount(); i++){
			var item = formsToChanges.item(i);
			//console.log(item.dom.id +'!=='+ selectedForm);
			if(item.dom.id !== selectedForm) {
				item.setDisplayed('none');
			}
			else{
				item.setDisplayed('block');
			}
		};
	}
	,updateWistListCounter: function(addOrRemove){
		var wishlistItemsCountDiv = Ext.get('wishlistItemsCount');
		
		if(wishlistItemsCountDiv !== null){
			var wishlistItemsCount = wishlistItemsCountDiv.dom.innerHTML;
			if(addOrRemove == 'add')
				wishlistItemsCount++;
			else
				wishlistItemsCount--;
				
			wishlistItemsCountDiv.dom.innerHTML = wishlistItemsCount;
		}
		
		
	}
	,radioChackBoxCombination: function(elementsClass){
		var FieldsClass = "." + elementsClass;
		
		Ext.select(FieldsClass).on('click', function(e, t) {
			
			//set(Ext.select(regionFieldsClass), )
			//Ext.select(regionFieldsClass).setChecked('false');
			var fieldsList = Ext.select(FieldsClass);
			if(t.type == 'radio'){
				for(i=0; i < fieldsList.getCount(); i++){
					var item = fieldsList.item(i);
					item.dom.checked = false;
				}
				t.checked = true;
			}
			else{
				var radiosList = fieldsList.filter('input[type=radio]');
				//alert(radiosList.getCount());
				for(i=0; i < radiosList.getCount(); i++){
					var radioItem = radiosList.item(i);
					radioItem.dom.checked = false;
				}
				
				if(t.checked == false){
					t.checked = false;
				}
				else{
					t.checked = true;
				}
			}
		});
	}
	,radioSearchByNameEvents: function(radioClass){
		Ext.select(radioClass).on('change', function(e, t) {
			this.radioSearchByNameChange(t.value)
		}, this);
	}
	,radioSearchByNameChange: function(selectedEl){
		if(this.idForm == '')
			this.idForm = 'searchByNameForm';
		
		//alert(this.idForm);
		var searchForm = Ext.get(this.idForm);
		
		if(searchForm !== null)
			if(Ext.get(selectedEl + 'URL') !== null) {
				searchForm.dom.action = Ext.get(selectedEl + 'URL').dom.value;
			}
			else {
				searchForm.dom.action = '/'+selectedEl+'/search.cfm';
			}
		
		if(selectedEl == 'hotels') {
			if(Ext.get('radioSearchByNameHotel') !== null)
				Ext.get('radioSearchByNameHotel').dom.checked = true;
		}
		else {
			if(Ext.get('radioSearchByNameVilla') !== null)
				Ext.get('radioSearchByNameVilla').dom.checked = true;
		}
		
	}
	,inputValidation: function(formEl,valType){
		var alpha = /^[a-zA-Z_]+$/;
		var alphanum = /^[a-zA-Z0-9_]+$/;
		var email = /^(\w+)([-+.][\w]+)*@(\w[-\w]*\.){1,5}([A-Za-z]){2,4}$/;
		var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
		
		if(valType == 'password'){
			formEl = Ext.get(formEl.id+'_hidde');
		}
		
		var valElem = formEl.getValue();
		
		if(valElem == ''){
			val = false;
		}
		else{
			if(valType == 'alpha'){
				val = alpha.test(valElem);
			}
			else if(valType == 'alphanum'){
				val = alphanum.test(valElem);
			}
			else if(valType == 'email'){
				val = email.test(valElem);
			}
			else if(valType == 'url'){
				val = url.test(valElem);
			}
			else if(valType == ''){
				val = true;
			}
			else{
				val = true;
			}
		}
		//console.log(valElem+ ' type: '+valType+' = '+val);
		return val;
	}
	,refreshPage: function(timeAt){
		
		var time = 500;
		
		if(timeAt !== undefined){
			var time = timeAt;
		}

		//alert('reload');
		(function(){
			//alert(window.location.hash);
			//console.log(window.location.hash);
			if(window.location.hash !== undefined && window.location.hash !== ''){
				var windowURL = document.URL.replace(window.location.hash,'');
			}
			else{
				var windowURL = document.URL;
			}
		
			window.location.href = windowURL;
			//window.location.reload();
         }).createDelegate(this).defer(time);
		 
		//window.location.reload();
	}
	,sortByEvents: function(elementsArr, formID, hiddenFieldID){
		this.sortByElementsArr = elementsArr;
		this.sortByHiddenField = Ext.get(hiddenFieldID);
		this.sortByformToSubmit = document.getElementById(formID);

		for(i=0; i < elementsArr.length; i++){
			var item = elementsArr[i];
			
			//Select events
			item.on('select', function(e, el, o){
				var sortByEl = e.id.replace(/sortBy_/, "");
				
				//var sortByElArr = e.id.split('_');
				//var sortByEl = sortByElArr[1];
				
				//Clear select values
				for(i=0; i < elementsArr.length; i++){
					var itemRe = elementsArr[i];
					if (itemRe.id !== e.id){
						itemRe.setValue('');
					}
				}
				
				//Set value to hidden field
				this.sortByHiddenField.dom.value = sortByEl +' '+e.getValue();
				
				//submit Sort By form
				this.sortByformToSubmit.submit();
			}, this);
		}
	}
	,sortByClear: function(){
		//Clear select values
		for(i=0; i < this.sortByElementsArr.length; i++){
			var itemRe = this.sortByElementsArr[i];
			itemRe.setValue('');

		}
		this.sortByHiddenField.dom.value = '';
		
		//submit Sort By form
		this.sortByformToSubmit.submit();
	}
	
	,enableKey: function() {
		Ext.fly(document).on('keydown', this.keyAction, this);
	}

	,disableKey: function() {
		Ext.fly(document).un('keydown', this.keyAction, this);
	}

	,keyAction: function(ev) {
		var keyCode = ev.getKey();

		if (
			keyCode == 13 //enter
		) {
			if(this.action !== undefined && ev.target.type !== 'textarea'){
				this.onClickSubmitEvent();
			}
		}
	}
	,setPanelContainsForm: function(slidePanelElAt){
		this.slidePanelEl = slidePanelElAt;
	}
	,closePanelWithTimeOut: function(){
		if(this.slidePanelEl !== ''){
          	(function(){
				this.slidePanelEl.closePanel();
           	}).createDelegate(this).defer(2000);
			
		}
	}
/*-------------------------------------------------*/
	

};
/*
Sardegna2
AjaxRequests JS
 
All material herein (c) Copyright 2009 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Rob
 
Changes (incl. date and name)
8/27/09 Luk: created
 
Purpose and Notes:
Required Parameters:
Optional Parameters:
Returns:

Class: AjaxRequests

Method:


*/

AjaxRequests = function() {
};

AjaxRequests.prototype = {
	 getContentContainerID: ''
	,getContentFormId: ''
	,getContentFileUrl: ''
	,loaderEl: ''
	,init: function(getContentContainerID, getContentFormId, getContentFileUrl, loaderIdAt){
		this.getContent = true;
		this.getContentContainerID = getContentContainerID;
		this.getContentFormId = getContentFormId;
		this.getContentFileUrl = getContentFileUrl;
		
		if(loaderIdAt !== undefined){
			this.loaderEl = Ext.get(loaderIdAt);
		}
		
	}
	,getContentRequest: function(){
		
		if(this.loaderEl !== null){
			this.loaderEl.dom.style.display = 'block';
		}
	
		Ext.Ajax.request({
		    form: this.getContentFormId,
			url: this.getContentFileUrl,
			success: function(response, opts) {
		      var responseObj = Ext.decode(response.responseText);
			  
			  if(this.loaderEl !== null){
			 	 this.loaderEl.dom.style.display = 'none';
			  }
			  
			  Ext.get(this.getContentContainerID).update(responseObj.content);
			 
			  if(responseObj.nextRequest !== undefined && responseObj.nextRequest !== "" && responseObj.nextRequest !== false){
				eval('this.'+responseObj.nextRequest+'("'+responseObj.data+'")');
			  }
			  
			  //this.responseRequest(responseObj);
		      //console.dir(obj);
		   },
		   failure: function(response, opts) {
		      alert('server-side failure with status code ' + response.status);
		   },
		   scope: this
		});
	}
	,setPrevNextEvents: function(onClickAction, prevButtonClass, nextButtonClass){
		
		if(prevButtonClass !== undefined){
			Ext.select('.'+prevButtonClass).on('click', function(e, t) {
				if(onClickAction == 'villaAvailability'){
					this.villaAvailabilityOnClick(t);
				}
				else if(onClickAction == 'homeSpecials'){
					this.homeSpecialsOnClick(t);
				}
				
			}, this);
		}
		
		if(nextButtonClass !== undefined){
			Ext.select('.'+nextButtonClass).on('click', function(e, t) {
				if(onClickAction == 'villaAvailability'){
					this.villaAvailabilityOnClick(t);
				}
				else if(onClickAction == 'homeSpecials'){
					this.homeSpecialsOnClick(t);
				}
			}, this);
		}
	
		
	}
	,updateVillaAvailabilityFields: function(data){
		//update date field after request
		Ext.get('dateToCheck').set({value: data});
		//set prev and next buttons events
	
		this.setPrevNextEvents('villaAvailability','villaAv_prevButton', 'villaAv_nextButton');
	
	}
	,updateHomeSpecialsvilla: function(data){
		Ext.get('villaSpecialObjectID').set({value: data});
		this.setPrevNextEvents('homeSpecials','villaspecial_prevButton', 'villaspecial_nextButton');
	}
	,updateHomeSpecialshotel: function(data){
		Ext.get('hotelSpecialObjectID').set({value: data});
		this.setPrevNextEvents('homeSpecials','hotelspecial_prevButton', 'hotelspecial_nextButton');
	}
	,updateEmailDetailsStatus: function(data){
		var imageEmailDetails = Ext.get(data);
		imageEmailDetails.dom.src = 'http://files1.sardegna-images.com/layouts/img/email_read.gif';
	}
	,villaAvailabilityOnClick: function(t){
		var targetIdArr = t.id.split('_');
		var date = targetIdArr[targetIdArr.length - 1];
		Ext.get('dateToCheck').set({value: "{d '"+date+"'}"});
		this.getContentRequest();
	}
	,homeSpecialsOnClick: function(t){
		var targetIdArr = t.id.split('_');
		var objekt = targetIdArr[targetIdArr.length - 1];
		var objektType = targetIdArr[0];
		var fieldToUpdate = '';
		
		if(objektType == 'hotelspecial'){
			fieldToUpdate = 'hotelSpecialObjectID';
		}
		else if(objektType == 'villaspecial'){
			fieldToUpdate = 'villaSpecialObjectID';
		}
		
		Ext.get(fieldToUpdate).set({value: objekt});
		this.getContentRequest();
	}
	,updateSurvey: function(data){
		Ext.get('surveyData').set({value: data});
		this.setSurveyEvents();
	}
	,surveyOnClick: function(t){
		var targetIdArr = t.id.split('_');
		var data = targetIdArr[targetIdArr.length - 1];
		Ext.get('surveyData').set({value: "data"});
		this.getContentRequest();
	}
	,setSurveyEvents: function(){
		Ext.select('.survey_next').on('click', function(e, t) {
			this.surveyOnClick(t);
		}, this);
	}
	
};/*
Sardegna2
ShowPopup JS
 
All material herein (c) Copyright 2009 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Rob
 
Changes (incl. date and name)
8/27/09 Luk: created
 
Purpose and Notes:
Required Parameters:
Optional Parameters:
Returns:

Class: ShowPopup

Method:

*/

ShowPopup = function(idForm) {
    if(idForm) {
        this.init(idForm);
    }
};


ShowPopup.prototype = {
	popupClass: ''
	,alignPosition: ''
	,shiftX: 0
	,shiftY: 0
	,urlAjaxFile: ''
	,ajaxLanguage: ''
	,getFromAjax: false
	,init: function(popupClass, alignAt, shiftX, shiftY){
		
		if(popupClass !== undefined)
			this.popupClass = popupClass;
			
		if(alignAt !== undefined)
			this.alignPosition = alignAt;
			
		if(shiftX !== undefined)
			this.shiftX = shiftX;
			
		if(shiftY !== undefined)
			this.shiftY = shiftY;
			
		this.setPopupEvents();
		
	}
	,setPopupEvents: function(){
		
		Ext.select('.'+this.popupClass).on('mouseover', function(e, t) {
			
			var target = Ext.get(t.id);
			
			var shiftX = this.shiftX;
			var shiftY = this.shiftY;
			
			
			
			var el = this.getElementToEvent(t);
			
			if(this.alignPosition.search('r') !== -1){
				shiftX = (shiftX + target.getWidth());	
			}
			if(this.alignPosition.search('b') !== -1){
				shiftY = (shiftY + target.getHeight());
			}
			
			if(el[1] !== null){
				if(this.getFromAjax){
					this.ajaxRequestFn(el[0], el[1]);
				}
				el[1].setLocation((target.getX()+shiftX),(target.getY()+shiftY));
			}
		}, this);
		
		Ext.select('.'+this.popupClass).on('mouseout', function(e, t) {
			var el = this.getElementToEvent(t);
			if(el[1] !== null){
				el[1].setLocation(-2000,-2000);
			}
		}, this);
	}
	,getElementToEvent: function(t){
		var eventEl = Ext.get(t.id);
		var idArr = t.id.split('_');
		var idType = idArr[0];
		var idNo = idArr[idArr.length-1];
		var idTable = idArr[idArr.length-2];
		
		var elParam = new Array();
		elParam[0] = idNo;
		
		if(isNaN(Number(idTable))){
			var popupId = idType+'_popup_'+ idNo;
		}
		else{
			var popupId = idType+'_popup_'+ idTable +'_'+ idNo;
			elParam[1] = idTable;
		}
		
		var popupEl = Ext.get(popupId);
		
		var el = new Array();
		el[0] = elParam;
		el[1] = popupEl;
		
		return el;
	
	}
	,getAjaxContent: function(urlAjaxFileAt, langugeAt){
		this.getFromAjax = true;
		this.urlAjaxFile = urlAjaxFileAt;
		this.ajaxLanguage = langugeAt;
	}
	,ajaxRequestFn: function(elParamArr, popupElAt){
		
		if(this.urlAjaxFile !== '' && popupElAt.dom.innerHTML == ''){
			
			var loaderEl = Ext.DomHelper.append(popupElAt, {
                tag: 'img',
				src: 'http://files1.sardegna-images.com/layouts/img/lb-load.gif',
				alt: 'loading...'
            }, true);
			
			Ext.Ajax.request({
				url: this.urlAjaxFile,
				params: {param: elParamArr, language: this.ajaxLanguage },
				success: function(response, opts) {
					var responseObj = Ext.decode(response.responseText);
				 
					loaderEl.dom.style.display = 'none';
					
					popupElAt.dom.innerHTML = responseObj.content;

			   },
			   failure: function(response, opts) {
			      alert('server-side failure with status code ' + response.status);
			   },
			   scope: this
			});
		}
	}
};


	Ext.ns('Ext.ux');

Ext.override(Ext.form.Field, {
			msgTarget : 'under',
			invalidClass : 'SardegnaForm-invalid-field',
			labelStyle : 'font-size: 11px'
		});

Ext.override(Ext.form.BasicForm, {
	isValid : function() {
		var valid = true;
		this.items.each(function(f) {
			var cnt = f.findParentByType('s-fieldset');
			if (!cnt && !f.validate() || cnt && !cnt.collapsed && !f.validate()) {
				valid = false;
			}
		});
		return valid;
	}
});

Ext.override(Ext.Element, {
			unwrap : function(sel) {
				var parent = this.up(sel, 1);
				if (parent) {
					parent.insertSibling(this.dom, 'before');
					parent.remove();
				}
				return this.dom;
			}
		});

SardegnaForm = {
	url : '/lib/services/service.cfm',
	createStoreWithAdditionalValue : function(field, value, url) {
		var record = Ext.data.Record.create([{
					name : field + 'ID',
					type : 'int'
				}, {
					name : field
				}]);
		return new Ext.data.JsonStore({
					url : url || this.url,
					baseParams : {
						cmd : 'getComboData',
						field : field
					},
					recordDef : record,
					fields : record,
					fieldName : field,
					addValue : value,
					root : 'data',
					listeners : {
						'load' : function(store, records, options) {
							var o = {};
							o[store.fieldName + 'ID'] = 0;
							o[store.fieldName] = store.addValue;
							store.insert(0, new store.recordDef(o));
							store.fireEvent('customload', store, records,
									options);
						}
					}
				});
	},
	createStore : function(field, url) {
		return new Ext.data.JsonStore({
					url : url || this.url,
					baseParams : {
						cmd : 'getComboData',
						field : field
					},
					fields : [{
								name : field + 'ID',
								type : 'int'
							}, {
								name : field
							}],
					root : 'data'
				})
	},
	generateArray : function(to, from) {
		var result = [];
		for (var i = from || 0; i <= to; i++) {
			result.push([i]);
		}
		return result;
	}
};

Ext.ux.SardegnaForm = Ext.extend(Ext.FormPanel, {
	url : SardegnaForm.url,
	border : false,
	labelAlign : 'top',
	translations : {},
	unstyled : true,
	initComponent : function() {
	},
	cls : 'Sardegna-Form',
	createItems : function() {
		Ext.ux.SardegnaForm.superclass.initComponent.apply(this, arguments);
		this.on({
					afterrender : {
						fn : this.onAfterRender,
						scope : this
					},
					show : {
						fn : this.scrollToTop
					}
				});
	},
	render : function() {
		if (!this.rendered) {
			var p = {
				cmd : 'getTranslations',
				translations : Ext.encode(this.translations)
			};
			if (this.pageName)
				Ext.apply(p, {
							page : this.pageName
						});
			Ext.Ajax.request({
						url : this.url,
						success : this.onGetTranslations,
						scope : this,
						params : p
					});
		}
	},
	onGetTranslations : function(response, action) {
		var jsonResponse = {};
		try {
			jsonResponse = Ext.decode(response.responseText);
		} catch (e) {
		}
		if (jsonResponse.success && jsonResponse.translations) {
			Ext.apply(this, {
						translations : jsonResponse.translations
					});
			this.createItems();
			Ext.ux.SardegnaForm.superclass.render.call(this, this.renderToEl);
		}
	},
	onAfterRender : function() {
		if (this.loadingIndicatorId && Ext.get(this.loadingIndicatorId))
			Ext.get(this.loadingIndicatorId).remove();
	},
	onSuccess : function(response, options) {
		var jsonResponse = {};
		try {
			jsonResponse = Ext.decode(response.responseText);
		} catch (e) {
		}
		return jsonResponse;
	},
	hideField : function(field) {
		if (field) {
			var f = this.getForm().findField(field);
			if (f && f.container) {
				var cnt = f.container.up('div.x-form-item');
				cnt.setVisibilityMode(Ext.Element.DISPLAY);
				cnt.hide();
			}
		}
	},
	showField : function(field) {
		if (field) {
			var f = this.getForm().findField(field);
			if (f && f.container) {
				var cnt = f.container.up('div.x-form-item');
				cnt.show();
			}
		}
	},
	scrollToTop : function() {
		if (document.body && document.body.scrollTop) {
			document.body.scrollTop = 0;
		} else if (document.documentElement
				&& document.documentElement.scrollTop) {
			document.documentElement.scrollTop = 0;
		}
	},
	onFailure : function(response, request) {
		var errMsg = "Unknown error."
		if (request.failureType === Ext.form.Action.CLIENT_INVALID) {
			errMsg = "Fill all required fileds!";
		} else {
			errMsg = "\nAjax communication failed.\n\n"
			switch (response.status) {
				case -1 :
					errMsg += "Request timed out.\n\nPlease try again.";
					break;
				case 0 :
					errMsg += "Check your internet connection.";
					break;
				case 500 :
					errMsg += "Internal server error.\n\n\n"
							+ response.responseText.substr(
									response.responseText.lastIndexOf('<pre>')
											+ 5, 2500);
					break;
			}
		}
		alert(errMsg);
	},
	createStoreWithAdditionalValue : SardegnaForm.createStoreWithAdditionalValue,
	createStore : SardegnaForm.createStore,
	generateArray : SardegnaForm.generateArray
});

Ext.override(Ext.layout.FormLayout, {
	labelSeparator : '',
	fieldTpl : new Ext.Template(
			'<div class="x-form-item {itemCls}" tabIndex="-1">',
			'<label for="{id}" style="{labelStyle}" class="x-form-item-label">{label}{required}{labelSeparator}</label>',
			'<div class="x-form-element" id="x-form-el-{id}" style="{elementStyle}">',
			'</div><div class="{clearCls}"></div>', '</div>'),
	getTemplateArgs : function(field) {
		var noLabelSep = !field.fieldLabel || field.hideLabel;
		return {
			id : field.id,
			label : field.fieldLabel,
			labelStyle : this.getLabelStyle(field.labelStyle),
			elementStyle : this.elementStyle || '',
			labelSeparator : noLabelSep
					? ''
					: (typeof field.labelSeparator == 'undefined'
							? this.labelSeparator
							: field.labelSeparator),
			itemCls : (field.itemCls || this.container.itemCls || '')
					+ (field.hideLabel ? ' x-hide-label' : ''),
			clearCls : field.clearCls || 'x-form-clear-left',
			required : field.allowBlank
					|| !(field.fieldLabel && field.fieldLabel.length)
					? ''
					: '<span style="color:#c90002;">*</span>'
		};
	}
});

Ext.ux.STextField = Ext.extend(Ext.form.TextField, {
			fieldClass : 'SardegnaForm-TextField',
			height : 19
		});
Ext.reg('s-textfield', Ext.ux.STextField);

Ext.ux.STextArea = Ext.extend(Ext.form.TextArea, {
			fieldClass : 'SardegnaForm-TextArea',
			focusClass : 'SardegnaForm-focus'
		});
Ext.reg('s-textarea', Ext.ux.STextArea);

Ext.ux.SIntegerField = Ext.extend(Ext.form.NumberField, {
			fieldClass : 'SardegnaForm-TextField',
			height : 19,
			allowNegative : false,
			allowDecimals : false
		});
Ext.reg('s-integerfield', Ext.ux.SIntegerField);

Ext.ux.SNumericField = Ext.extend(Ext.form.NumberField, {
			fieldClass : 'SardegnaForm-TextField',
			height : 19,
			allowNegative : false
		});
Ext.reg('s-numericfield', Ext.ux.SNumericField);

Ext.ux.SSpacer = Ext.extend(Ext.Spacer, {
			cls : 'SardegnaForm-Spacer'
		});
Ext.reg('s-spacer', Ext.ux.SSpacer);

Ext.ux.SComboBox = Ext.extend(Ext.form.ComboBox, {
			fieldClass : 'SardegnaForm-ComboBox-field',
			listClass : 'SardegnaForm-ComboBox-list',
			selectedClass : 'SardegnaForm-ComboBox-selected',
			triggerClass : 'SardegnaForm-ComboBox-trigger',
			height : 19,
			editable : false,
			triggerAction : 'all'
		});
Ext.reg('s-combobox', Ext.ux.SComboBox);

Ext.ux.SDateField = Ext.extend(Ext.form.DateField, {
			fieldClass : 'SardegnaForm-ComboBox-field',
			triggerClass : 'SardegnaForm-DateField-trigger',
			height : 19,
			editable : false,
			allowBlank : false,
			format : 'd.m.Y'
		});
Ext.reg('s-datefield', Ext.ux.SDateField);

Ext.ux.SFieldSet = Ext.extend(Ext.form.FieldSet, {
	baseCls : 'SardegnaForm-Fieldset',
	collapsed : true,
	collapse : function(animate) {
		Ext.each(this.findByType(Ext.form.Field), function(f) {
					f.clearInvalid();
				});
		Ext.form.FieldSet.superclass.collapse.apply(this, arguments);
	},
	onRender : function(ct, position) {
		if (!this.el) {
			this.el = document.createElement('fieldset');
			this.el.id = this.id;
			if (this.title || this.header || this.checkboxToggle) {
				this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header';
			}
		}

		Ext.form.FieldSet.superclass.onRender.call(this, ct, position);

		if (this.checkboxToggle) {
			var obj = {
				tag : 'input',
				type : 'checkbox',
				name : this.checkboxName || this.id + '-checkbox'
			};
			if (this.tabIndex && (this.tabIndex > 0 || this.tabIndex === 0))
				Ext.apply(obj, {
							tabIndex : this.tabIndex
						});
			var o = typeof this.checkboxToggle == 'object'
					? this.checkboxToggle
					: obj;
			this.checkbox = this.header.insertFirst(o);
			this.checkbox.dom.checked = !this.collapsed;
			this.mon(this.checkbox, 'click', this.onCheckClick, this);
		}
	}
});
Ext.reg('s-fieldset', Ext.ux.SFieldSet);

Ext.ux.HeaderLabel = Ext.extend(Ext.form.Label, {
			cls : 'SardegnaForm-HeaderLabel'
		});
Ext.reg('hlabel', Ext.ux.HeaderLabel);

Ext.ux.LinkLabel = Ext.extend(Ext.form.Label, {
			cls : 'SardegnaForm-LinkLabel',
			overCls : 'SardegnaForm-LinkLabel-over'
		});
Ext.reg('llabel', Ext.ux.LinkLabel);

Ext.override(Ext.Button, {
	buttonSelector : 'span:first-child',
	autoWidth : true,
	template : new Ext.Template(
			'<table cellspacing="0" class="x-btn"><tbody class="{4}">',
			'<tr><td class="x-btn-ml"><i>&#160;</i></td><td class="x-btn-mc"><em class="{5}" unselectable="on"><span class="SardegnaForm-Button">{0}</span></em></td><td class="x-btn-mr"><i>&#160;</i></td></tr>',
			"</tbody></table>")
});

Ext.ux.SLoadMask = Ext.extend(Ext.LoadMask, {
			msgCls : 'loading-indicator',
			msg : 'Loading...',
			onLoad : function() {
				// this.el.unmask(this.removeMask);
			},
			onBeforeLoad : function() {
				if (!this.disabled) {
					var li = new Ext.BoxComponent({
								autoEl : {
									id : 'formLoadingIndicator',
									tag : 'div',
									cls : this.msgCls,
									html : this.msg
								}
							});
					// console.log(li);
					// li.appendTo(this.el);
					// this.el.appendChild('<div id="test"></div>');
				}
			}
		});
Ext.ns('Ext.ux');

Ext.ux.Login = Ext.extend(Ext.ux.SardegnaForm, {
	translations : {
		email : 'Email',
		password : 'Password',
		logIn : 'Log in',
		passwordRemind : 'Forgot your password?',
		pleaseWait : 'Please wait...',
		sendPassword : 'Send password'
	},
	createItems : function() {
		this.submitAction = 'userLogin';
		this.actions = {
			submit : new Ext.Action({
						text : this.translations.logIn,
						handler : this.onSubmit,
						scope : this,
						width : 120
					})
		};
		Ext.apply(this, {
					items : [{
								xtype : 's-textfield',
								name : 'username',
								fieldLabel : this.translations.email,
								vtype : 'email',								
								width : 225
							}, {
								xtype : 's-textfield',
								name : 'password',
								fieldLabel : this.translations.password,
								inputType : 'password'
							}, {
								itemId : 'passwordRemindLabel',
								xtype : 'llabel',
								text : this.translations.passwordRemind,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
														click : {
															fn : this.onForgotPassword,
															scope : this
														}
													});
										},
										scope : this
									}
								}
							}],
					buttons : [this.actions.submit],
					buttonAlign : 'right'
				});
		Ext.ux.Login.superclass.createItems.apply(this, arguments);
	},
	onSubmit : function() {
		this.getForm().submit({
					url : this.url,
					success : this.onSubmitSuccess,
					failure : this.onSubmitFailure,
					scope : this,
					params : {
						cmd : this.submitAction
					}
				});
		this.actions.submit.setText(this.translations.pleaseWait);
		this.actions.submit.disable();
	},
	setUsername : function(username) {
		if (username) {
			var f = this.getForm().findField('username');
			if (f)
				f.setValue(username);
			f = this.getForm().findField('password');
			if (f)
				f.focus(false, 200);
		}
	},
	onSubmitSuccess : function(form, response) {
		if (response.options.params.cmd === 'userRemindPassword') {
			this.showField('password');
			var l = this.getComponent('passwordRemindLabel');
			if (l)
				l.show();
			this.actions.submit.setText(this.translations.logIn);
			this.actions.submit.enable();
			this.submitAction = 'userLogin';
			var f = this.getForm().findField('password');
			if (f)
				f.reset();
		} else if (response.options.params.cmd === 'userLogin') {
			location.reload();
		}
	},
	onSubmitFailure : function(form, response) {
		if (response.result && response.result.msg) {
			var f = this.getForm().findField('username');
			if (f)
				f.markInvalid(response.result.msg);
			this.actions.submit
					.setText(response.options.params.cmd === 'userLogin'
							? this.translations.logIn
							: this.translations.sendPassword);
			this.actions.submit.enable();
		}
	},
	onForgotPassword : function() {
		var l = this.getComponent('passwordRemindLabel');
		if (l)
			l.hide();
		var f = this.getForm().findField('username');
		if (f)
			f.clearInvalid();
		this.hideField('password');
		this.actions.submit.setText(this.translations.sendPassword);
		this.submitAction = 'userRemindPassword';
	}/*
		 * , setFieldsDisabled : function(disable) { Ext.each(['username',
		 * 'password'], function(id) { var f = this.getForm().findField(id); if
		 * (f) f.setDisabled(disable); return true; }, this) }
		 */
});
Ext.ns('Ext.ux');

Ext.ux.Travelers = Ext.extend(Ext.Container, {
	translations : null,
	travelersGroup : '',
	relatedGroup : '',
	trvTabIndex : 3000,
	trvFirstName : 'travelerFirstName',
	trvLastName : 'travelerLastName',
	trvBirthDate : 'travelerBirthDate',
	trvSelected : 'travelerSelected',
	trvelersNameWidth : 200,
	maxAdultsTravelers : 2,
	maxChildrenTravelers : 2,
	travelersCounter : 0,
	collapsed : true,
	initComponent : function() {

		Ext.apply(this, {
					items : [{
						xtype : 'container',
						itemId : String.format('cnt{0}Travelers',
								this.travelersGroup),
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}
					/*
					 * , { xtype : 'llabel', text :
					 * this.translations.addTraveler, listeners : { afterrender : {
					 * fn : function(cmp) { cmp.getEl().on({ click : { fn :
					 * this.onAddTraveler, scope : this } }); }, scope : this } } }
					 */
					]
				});

		Ext.ux.Travelers.superclass.initComponent.apply(this, arguments);
		this.on({
					afterrender : this.addRemoveTravelers,
					scope : this
				});
	},
	onAddTraveler : function() {
		var cnt = this.getComponent(String.format('cnt{0}Travelers',
				this.travelersGroup));
		this.travelersCounter++;
		if (cnt) {
			if (this.travelersCounter === 1)
				cnt.add({
					defaults : {
						xtype : 'container',
						defaults : {
							xtype : 'label',
							style : 'font-size: 11px'
						}
					},
					items : [{
								columnWidth : 0.35,
								items : [{
											text : this.translations.travelerFirstName
										}]
							}, {
								columnWidth : 0.35,
								items : [{
											text : this.translations.travelerLastName
										}]
							}, {
								columnWidth : 0.2,
								items : [{
											text : this.translations.travelerBirthDate
										}]
							}, {
								columnWidth : 0.1,
								items : [{
											text : this.translations.travelerSelected
										}]
							}]
				});
			cnt.add({
						id : String.format('{0}TravelerRow_{1}',
								this.travelersGroup, this.travelersCounter),
						realtedGroup : this.relatedGroup,
						defaults : {
							xtype : 'container',
							layout : 'form',
							labelAlign : 'top',
							defaults : {
								tabIndex : this.trvTabIndex,
								hideLabel : true,
								allowBlank : false,
								trvIdx : this.travelersCounter,
								listeners : {
									blur : function(fld) {
										this.fillRelatedField(fld,
												this.relatedGroup);
									},
									afterrender : this.onAfterrenderField,
									scope : this
								}
							}
						},
						items : [{
							columnWidth : 0.35,
							items : [{
								itemIndex : 0,
								id : String.format('{0}_{1}{2}',
										this.travelersGroup, this.trvFirstName,
										this.travelersCounter),
								xtype : 's-textfield',
								name : String.format('{0}_{1}_{2}',
										this.travelersGroup, this.trvFirstName,
										this.travelersCounter),
								width : this.trvelersNameWidth
							}]
						}, {
							columnWidth : 0.35,
							items : [{
								itemIndex : 1,
								id : String.format('{0}_{1}{2}',
										this.travelersGroup, this.trvLastName,
										this.travelersCounter),
								xtype : 's-textfield',
								name : String.format('{0}_{1}_{2}',
										this.travelersGroup, this.trvLastName,
										this.travelersCounter),
								width : this.trvelersNameWidth
							}]
						}, {
							columnWidth : 0.2,
							items : [{
								itemIndex : 2,
								xtype : 's-datefield',
								editable : true,
								id : String.format('{0}_{1}{2}',
										this.travelersGroup, this.trvBirthDate,
										this.travelersCounter),
								name : String.format('{0}_{1}_{2}',
										this.travelersGroup, this.trvBirthDate,
										this.travelersCounter)
							}]
						}, {
							columnWidth : 0.1,
							items : [{
								itemIndex : 3,
								xtype : 'checkbox',
								id : String.format('{0}_{1}{2}',
										this.travelersGroup, this.trvSelected,
										this.travelersCounter),
								name : String.format('{0}_{1}_{2}',
										this.travelersGroup, this.trvSelected,
										this.travelersCounter),
								checked : true,
								relatedFields : [
										String.format('{0}_{1}{2}',
												this.travelersGroup,
												this.trvFirstName,
												this.travelersCounter),
										String.format('{0}_{1}{2}',
												this.travelersGroup,
												this.trvLastName,
												this.travelersCounter),
										String.format('{0}_{1}{2}',
												this.travelersGroup,
												this.trvBirthDate,
												this.travelersCounter)],
								listeners : {
									blur : {
										fn : function(fld) {
										}
									},
									check : function(fld) {
										this.fillRelatedCheckbox(fld,
												this.relatedGroup);
									},
									afterrender : this.onAfterrenderField,
									scope : this
								}
							}]
						}/*
							 * , { columnWidth : 0.1, items : [{ xtype :
							 * 'llabel', text : this.translations.remove,
							 * listeners : { afterrender : { fn : function(cmp) {
							 * cmp.getEl().on({ click : { fn : function(ev,
							 * html, options) { var owner =
							 * cmp.ownerCt.ownerCt.ownerCt; owner.remove(
							 * cmp.ownerCt.ownerCt, true); owner.doLayout(); },
							 * scope : cmp } }); }, scope : this } } }] }
							 */]
					});
			if (this.collapsed)
				this.doLayoutOnExpand = true;
			else
				cnt.doLayout();
		}
	},
	onRemoveTraveler : function() {
		var cnt = this.getComponent(String.format('cnt{0}Travelers',
				this.travelersGroup));
		if (cnt && this.travelersCounter > 0) {
			cnt.remove(String.format('{0}TravelerRow_{1}', this.travelersGroup,
							this.travelersCounter), true);
			cnt.doLayout();
			this.travelersCounter--;
		}
	},
	setMaxAdultsTravelers : function(n) {
		this.maxAdultsTravelers = parseInt(n);		
		if (this.rendered)
			this.addRemoveTravelers();
	},
	setMaxChildrenTravelers : function(n) {
		this.maxChildrenTravelers = parseInt(n);
		if (this.rendered)
			this.addRemoveTravelers();
	},
	addRemoveTravelers : function() {
		if (this.rendered) {			
			if (this.maxAdultsTravelers + this.maxChildrenTravelers > this.travelersCounter)
				for (var i = this.travelersCounter; i < this.maxAdultsTravelers
						+ this.maxChildrenTravelers; i++)
					this.onAddTraveler();
			else
				for (var i = this.travelersCounter; i > this.maxAdultsTravelers
						+ this.maxChildrenTravelers; i--)
					this.onRemoveTraveler();
		}
	},
	fillRelatedField : function(fld, group) {
		var cnt = Ext.getCmp(String.format('{0}TravelerRow_{1}', group,
				fld.trvIdx));
		if (cnt && fld.itemIndex >= 0)
			cnt.items.itemAt(fld.itemIndex).items.itemAt(0).setRawValue(fld
					.getRawValue());
	},
	fillRelatedCheckbox : function(fld, group) {
		if (fld.relatedFields) {
			for (var i = 0, len = fld.relatedFields.length; i < len; i++) {
				var f = Ext.getCmp(fld.relatedFields[i])
				f.allowBlank = fld.getValue() ? false : true;
				if (!fld.getValue())
					f.clearInvalid();
			}
		}
		/*
		 * var cnt = Ext.getCmp(String.format('{0}TravelerRow_{1}', group,
		 * fld.trvIdx)); if (cnt && fld.itemIndex >= 0) { var chbox =
		 * cnt.items.itemAt(fld.itemIndex).items.itemAt(0);
		 * chbox.setValue(!fld.getValue()); }
		 */
	},
	onAfterrenderField : function(fld) {
		var cntRel = Ext.getCmp(String.format('{0}TravelerRow_{1}',
				this.relatedGroup, fld.trvIdx));
		if (cntRel && fld.itemIndex >= 0) {
			var fldRel = cntRel.items.itemAt(fld.itemIndex).items.itemAt(0);
			if (fldRel) {
				if (fldRel instanceof Ext.form.Checkbox) {
					/*
					 * fld.setDisabled(this.getRelatedComponent().collapsed); if
					 * (this.getRelatedComponent().collapsed)
					 * this.fillRelatedCheckbox.defer(50, this, [fld,
					 * this.relatedGroup]); else
					 * this.fillRelatedCheckbox.defer(50, this, [fldRel,
					 * cntRel.realtedGroup]);
					 */
				} else
					this.fillRelatedField.defer(50, this, [fldRel,
									cntRel.realtedGroup]);
			}
		} /*
			 * else if (fld instanceof Ext.form.Checkbox) fld.disable();
			 */
	},
	fillEnableAll : function(fill/* , enable */) {
		Ext.each(this.findByType('checkbox'), function(chbox) {
					/* chbox.setDisabled(!enable); */
					if (fill)
						chbox.setValue(true);
				});
	},
	setExpanded : function() {
		this.collapsed = false;
		if (this.doLayoutOnExpand) {
			this.doLayout();
			this.doLayoutOnExpand = false;
		}
		this.fillEnableAll(true);
		/*
		 * var cmpRel = this.getRelatedComponent();
		 * this.fillEnableAll(cmpRel.collapsed, !cmpRel.collapsed); if
		 * (!cmpRel.collapsed) cmpRel.fillEnableAll(false, true);
		 */
	},
	setCollapsed : function() {
		this.collapsed = true;
		this.fillEnableAll(false);
		/*
		 * var cmpRel = this.getRelatedComponent(); if (cmpRel)
		 * cmpRel.fillEnableAll(true, false);
		 */
	},
	getRelatedComponent : function() {
		return Ext.getCmp(this.relatedGroup + 'TravelersComponent');
	}
});

Ext.reg('s-travelers-group', Ext.ux.Travelers);Ext.ns('Ext.ux');

Ext.ux.HotelSpecificData = Ext.extend(Ext.Container, {
	defaults : {
		layout : 'form',
		xtype : 'container',
		labelAlign : 'top'
	},
	style : {
		'margin-bottom' : '5px'
	},
	forceSelection : false,
	initComponent : function() {

		this.roomCategoryField = "roomCategory";
		this.roomCategoryStore = new Ext.data.JsonStore({
					url : this.url,
					baseParams : {
						cmd : 'getRoomCategories'
					},
					fields : [{
								name : this.roomCategoryField + 'ID',
								type : 'int'
							}, {
								name : this.roomCategoryField
							}, {
								name : 'roomPrice',
								type : 'float'
							}],
					root : 'data'
				});

		this.boardStore = new Ext.data.JsonStore({
			url : this.url,
			baseParams : {
				cmd : 'getBoardRadios',
				hotelID : this.hotelID
			},
			fields : [{
						name : 'boxLabel'
					}, {
						name : 'inputValue'
					}, {
						name : 'available'
					}],
			root : 'data',
			idProperty : 'inputValue',
			autoLoad : true,
			listeners : {
				'load' : {
					fn : function(store, records, options) {
						if (store.reader.jsonData
								&& store.reader.jsonData.hotelName) {

							if (store.reader.jsonData.boardArrDate
									&& store.reader.jsonData.boardDepDate) {
								this.arrivalDate = store.reader.jsonData.boardArrDate;
								this.departureDate = store.reader.jsonData.boardDepDate;
							}

							var cnt = this.getComponent('cntHotelName');
							if (cnt) {
								cnt.removeAll(true);
								cnt.add({
									xtype : 'box',
									autoEl : {
										tag : 'span',
										html : String
												.format(
														'<span style="{2}">{0}: </span><div style="font-weight: bold; {3}">{1} {4} {5}</div>',
														store.reader.jsonData.hotelName,
														store.reader.jsonData.hotelClosed
																? this.translations.hotelClosed
																: '',
														store.reader.jsonData.hotelClosed
																? 'color: gray;'
																: '',
														// this.forceSelection ?
														!(!store.reader.jsonData.hotelClosed && store.reader.jsonData.predictedSeason)
																? 'color: #C90002;'
																: '',
														store.reader.jsonData.hotelClosed
																&& store.reader.jsonData.hotelSeasonStart
																&& store.reader.jsonData.hotelSeasonEnd
																? String
																		.format(
																				'({0} {1} {2} {3})',
																				this.translations.hotelIsAvailable,
																				store.reader.jsonData.hotelSeasonStart,
																				this.translations.availableTo,
																				store.reader.jsonData.hotelSeasonEnd)
																: '',
														!store.reader.jsonData.hotelClosed
																&& store.reader.jsonData.predictedSeason
																? String
																		.format(
																				'{0} {1} {2}',
																				this.translations.subjectToChanges,
																				store.reader.jsonData.predictedSeasonYear,
																				this.translations.notYetAvailable)
																: '')
									}
								});
								if (!store.reader.jsonData.hotelClosed)
									cnt.add({
												xtype : 'hidden',
												name : 'hotelName-'
														+ this.hotelID,
												value : store.reader.jsonData.hotelName
											});
								else
									this.disableRoomCategory(true, true);
								cnt.doLayout();
								this
										.grayOutRoomCategoryLabel(store.reader.jsonData.hotelClosed);
							}
						}
						var checkboxItems = [];
						var counter = 0;
						Ext.each(records, function(record, idx, all) {
									checkboxItems[counter] = record.data;
									Ext.apply(checkboxItems[counter], {
												name : 'board_' + this.hotelID,
												disabled : !record.data.available,
												inputValue : record.data.boxLabel,
												valueID : record.data.inputValue
											});
									counter++;
								}, this);
						var cnt = this.getComponent('cntBoardGroup');
						if (cnt) {
							cnt.removeAll(true);
							cnt.add({
								itemId : 'fldBoardGroup' + this.hotelID,
								xtype : 'checkboxgroup',
								allowBlank : (!store.reader.jsonData.hotelClosed
										|| this.hotelID === 0 || this.forceSelection)
										? false
										: true,
								blankText : this.translations.selectAtLeastOneItem,
								fieldLabel : this.translations.board,
								labelStyle : store.reader.jsonData.hotelClosed
										&& this.hotelID !== 0
										? 'color: gray'
										: '',
								items : checkboxItems,
								tabIndex : 2000,
								columns : 4,
								listeners : {
									change : function(group, newVal) {
										/*
										 * var cmb = this.getRoomCateogryFld();
										 * if (cmb) { cmb .setDisabled(!(newVal &&
										 * newVal.length)); cmb.emptyText =
										 * newVal && newVal.length ? '' :
										 * this.translations.roomCategoryEmpty;
										 * cmb.setRawValue(cmb.emptyText); }
										 */
										this.disableRoomCategory(
												!(newVal && newVal.length),
												!(newVal && newVal.length));
									},
									invalid : function(group, msg) {
										if (group && group.items) {
											var hasOption = false;
											group.items.each(function(i) {
														if (!i.disabled) {
															hasOption = true;
															return false;
														}
														return true;
													})
											if (!hasOption)
												group.clearInvalid();
										}
									},
									scope : this
								}
							});
							cnt.doLayout();
						}
						this.setMandatory(store.reader.jsonData.hotelClosed);
					},
					scope : this
				}
			}
		});

		var roomCategoryItems = [];
		if (this.hotelID)
			roomCategoryItems.push({
						itemId : 'fldRoomCategory' + this.hotelID,
						xtype : 's-combobox',
						hidden : this.hotelID === 0,
						fieldLabel : this.translations.roomCategory,
						mode : 'remote',
						store : this.roomCategoryStore,
						displayField : this.roomCategoryField,
						name : this.roomCategoryField + '_' + this.hotelID,
						valueField : this.roomCategoryField + 'ID',
						hiddenName : this.roomCategoryField + 'ID_'
								+ this.hotelID,
						editable : false,
						tabIndex : 100,
						queryParam : 'params',
						value : '',
						emptyText : this.translations.roomCategoryEmpty,
						disabled : true,
						width : 327,
						tpl : new Ext.XTemplate(
								'<tpl for="."><div class="x-combo-list-item">{'
										+ this.roomCategoryField
										+ '} ('
										+ this.translations.priceFrom
										+ ' {[this.showPrice(values.roomPrice)]} '
										+ this.translations.euroPersonDay
										+ ')</div></tpl>', {
									showPrice : function(price) {
										return Ext.util.Format.number(price,
												'0,00/i');
									}
								}),
						listeners : {
							beforequery : {
								fn : function(queryEvent) {
									if (this.arrivalDate && this.departureDate) {
										var boardArr = []
										this.getBoardGroupFld().items.each(
												function(item) {
													boardArr
															.push(item
																	.getValue()
																	? 1
																	: 0);
												});
										var args = {
											arrivalDate : this.arrivalDate,
											departureDate : this.departureDate,
											board : boardArr,
											hotelID : this.hotelID
										};
										var val = Ext.encode(args);
										queryEvent.cancel = (queryEvent.query == val);
										queryEvent.query = val;
									} else
										queryEvent.cancel = true;
								},
								scope : this
							}
						}
					});

		Ext.apply(this, {
					items : [{
								itemId : 'cntHotelName'
							}, {
								itemId : 'cntBoardGroup'
							}, {
								itemId : 'cntRoomCategory',
								items : roomCategoryItems
							}]
				});
		Ext.ux.HotelSpecificData.superclass.initComponent
				.apply(this, arguments);
	},
	updateBoard : function(arrival, departure) {
		this.arrivalDate = arrival;
		this.departureDate = departure;

		if (this.hotelID)
			this.boardStore.load({
						params : {
							arrivalDate : arrival,
							departureDate : departure
						}
					});
	},
	getBoardGroupFld : function() {
		return this.getComponent('cntBoardGroup').getComponent('fldBoardGroup'
				+ this.hotelID);
	},
	getRoomCateogryFld : function() {
		return this.getComponent('cntRoomCategory')
				.getComponent('fldRoomCategory' + this.hotelID);
	},
	setMandatory : function(isHotelClosed) {
		var roomCategory = this.getRoomCateogryFld();
		if (roomCategory)
			roomCategory.allowBlank = (isHotelClosed || !roomCategory
					.isVisible()) ? true : false;
	},
	disableRoomCategory : function(disable, setEmptyText) {
		var cmb = this.getRoomCateogryFld();
		if (cmb) {
			cmb.setDisabled(disable);
			cmb.emptyText = setEmptyText
					? this.translations.roomCategoryEmpty
					: '';
			cmb.setRawValue(cmb.emptyText);

		}
	},
	grayOutRoomCategoryLabel : function(grayOut) {
		var cmb = this.getRoomCateogryFld();
		if (cmb) {
			if (grayOut)
				cmb.container.prev('label').addClass('SardegnaForm-disabled');
			else
				cmb.container.prev('label')
						.removeClass('SardegnaForm-disabled');
		}
	}
});

Ext.reg('s-hotel-specific-data', Ext.ux.HotelSpecificData);

Ext.ux.HotelOffer = Ext.extend(Ext.Container, {
	translations : null,
	url : null,
	hotelsList : null,
	requestFromWishlist : false,
	layout : 'form',
	initComponent : function() {
		this.hasOneHotel = this.hotelsList.length === 1;
		this.hotelStarField = 'HOTELSTAR';
		this.hotelStarStore = SardegnaForm.createStoreWithAdditionalValue(
				this.hotelStarField, this.translations.any);

		this.hotelSizeField = 'HOTELSIZE';
		this.hotelSizeStore = SardegnaForm.createStore(this.hotelSizeField);

		this.maxPriceHotelField = 'MAXPRICEHOTEL';
		this.maxPriceHotelStore = SardegnaForm.createStoreWithAdditionalValue(
				this.maxPriceHotelField, this.translations.doesnotmatter);

		var hotelsDetails = [];

		for (var i = 0, len = this.hotelsList.length
				? this.hotelsList.length
				: 1; i < len; i++) {
			hotelsDetails.push({
						xtype : 's-hotel-specific-data',
						translations : this.translations,
						url : this.url,
						hotelID : this.hotelsList.length
								? this.hotelsList[i]
								: 0,
						forceSelection : this.hasOneHotel
								&& !this.requestFromWishlist ? true : false
					});
		}

		Ext.apply(this, {
			items : [{
				xtype : 'container',
				itemId : 'cntOwnerHotelRooms',
				layout : 'column',
				defaults : {
					xtype : 'container',
					layout : 'form',
					columnWidth : 0.33
				},
				hidden : this.hotelsList.length,
				items : [{
							items : [{
										xtype : 's-combobox',
										name : 'hotelStars',
										fieldLabel : this.translations.stars,
										mode : 'remote',
										store : this.hotelStarStore,
										displayField : this.hotelStarField,
										valueField : this.hotelStarField + 'ID',
										editable : false,
										tabIndex : 2000,
										allowBlank : this.hotelsList.length
									}]
						}, {
							items : [{
										id : 'cmb-hotel-size',
										xtype : 's-combobox',
										fieldLabel : this.translations.hotelSize,
										mode : 'remote',
										store : this.hotelSizeStore,
										displayField : this.hotelSizeField,
										name : this.hotelSizeField,
										valueField : this.hotelSizeField + 'ID',
										hiddenName : this.hotelSizeField + 'ID',
										editable : false,
										tabIndex : 2000,
										allowBlank : this.hotelsList.length
									}]
						}, {
							itemId : 'cntHotelRooms'
						}]
			}, {
				xtype : 'radiogroup',
				itemId : 'children-beds',
				name : 'hotel-children-beds',
				columns : 4,
				fieldLabel : this.translations.forChildren,
				tabIndex : 2000,
				items : [{
							boxLabel : this.translations.setBed,
							checked : true,
							name : 'forChildren',
							inputValue : 'setBed'
						}, {
							boxLabel : this.translations.seperateRoom,
							name : 'forChildren',
							inputValue : 'separateRoom'
						}],
				listeners : {
					afterrender : function() {
						if (this.parentformpanel
								&& this.childrenCount !== undefined) {
							if (this.childrenCount)
								this.parentformpanel
										.showField('hotel-children-beds');
							else
								this.parentformpanel
										.hideField('hotel-children-beds');
						}
					},
					scope : this
				}
			}, {
				xtype : 'container',
				itemId : 'hotelSpecificData',
				items : hotelsDetails
			}, {
				xtype : 'container',
				layout : 'form',
				hidden : this.hotelsList.length,
				items : [{
					xtype : 'container',
					itemId : 'cntHotelsDistanceToSea',
					layout : 'column',
					defaults : {
						xtype : 'container',
						layout : 'form'
					},
					items : [{
								columnWidth : .33,
								items : [{
											xtype : 'label',
											text : this.translations.distanceToSea
										}]
							}, {
								columnWidth : .66,
								items : [{
									xtype : 'checkboxgroup',
									hideLabel : true,
									allowBlank : this.hotelsList.length,
									id : 'hotelsDistanceToSeaGroup',
									columns : 3,
									tabIndex : 701,
									defaults : {
										actAsRadio : false,
										groupID : 'hotelsDistanceToSeaGroup',
										listeners : {
											check : {
												fn : this.onCheckOption,
												scope : this
											}
										}
									},
									items : [{
										// xtype : 'radio',
										name : 'hotelDistanceToSea',
										boxLabel : this.translations.anyDistance,
										checked : true,
										inputValue : this.translations.anyDistance,
										valueID : '5',
										actAsRadio : true
									}, {
										boxLabel : String.format('{0} 200m',
												this.translations.upTo),
										name : 'hotelDistanceToSea',
										inputValue : String.format('{0} 200m',
												this.translations.upTo),
										valueID : '1'
									}, {
										boxLabel : String.format('{0} 400m',
												this.translations.upTo),
										name : 'hotelDistanceToSea',
										inputValue : String.format('{0} 400m',
												this.translations.upTo),
										valueID : '2'
									}, {
										boxLabel : String.format('{0} 800m',
												this.translations.upTo),
										name : 'hotelDistanceToSea',
										inputValue : String.format('{0} 800m',
												this.translations.upTo),
										valueID : '3'
									}, {
										boxLabel : String.format('{0} 800m',
												this.translations.moreThan),
										name : 'hotelDistanceToSea',
										inputValue : String.format('{0} 800m',
												this.translations.moreThan),
										valueID : '4'
									}]
								}]
							}]
				}, {
					xtype : 's-combobox',
					fieldLabel : this.translations.maxHotelCosts,
					mode : 'remote',
					store : this.maxPriceHotelStore,
					displayField : this.maxPriceHotelField,
					name : this.maxPriceHotelField,
					valueField : this.maxPriceHotelField + 'ID',
					hiddenName : this.maxPriceHotelField + 'ID',
					tabIndex : 2000,
					allowBlank : this.hotelsList.length
				}]
			}, {
				xtype : 's-textarea',
				name : 'importantForHotel',
				fieldLabel : this.translations.importantForHotel,
				tabIndex : 2000,
				width : 589,
				height : 30
			}]
		});

		Ext.ux.HotelOffer.superclass.initComponent.apply(this, arguments);
	},
	showRooms : function(show) {
		var cnt = this.getComponent('cntOwnerHotelRooms')
				.getComponent('cntHotelRooms');
		if (cnt) {
			var cmpArray = cnt.findByType('combo');
			if (cmpArray.length === 0 && show) {
				cnt.add({
							xtype : 's-combobox',
							fieldLabel : this.translations.rooms,
							mode : 'local',
							store : {
								xtype : 'arraystore',
								autoDestroy : true,
								fields : [{
											name : 'rooms',
											type : 'int'
										}],
								data : SardegnaForm.generateArray(8, 1)
							},
							displayField : 'rooms',
							name : 'hotelRooms',
							tabIndex : 2000,
							allowBlank : this.hotelsList.length
						});
				cnt.doLayout();
			} else if (cmpArray.length && !show) {
				try {
					cnt.removeAll();
				} catch (ex) {
				}
				cnt.doLayout();
			}
		}
	},
	updateTravelDates : function(arrival, departure) {
		var hotelDataItems = this.findByType('s-hotel-specific-data');

		Ext.each(hotelDataItems, function(item) {
					item.updateBoard(arrival, departure);
				});
	},
	onCheckOption : function(fld, value) {
		if (value) {
			Ext.getCmp(fld.groupID).items.each(function(item) {
						if (item.actAsRadio == !fld.actAsRadio) {
							item.setValue(false);
						}
					});
		}
	},
	showChildrenBeds : function(formpanel, children) {
		this.childrenCount = children;
		this.parentformpanel = formpanel;
		if (children)
			formpanel.showField('hotel-children-beds');
		else
			formpanel.hideField('hotel-children-beds');
	}
});

Ext.reg('s-hotel-offer', Ext.ux.HotelOffer);Ext.ns('Ext.ux');

Ext.ux.PersonalData = Ext.extend(Ext.Container, {
	fieldWidth : 225,
	url : '',
	initComponent : function() {

		var localUrl = this.url;

		this.itemsToLoad = 1;

		this.languageField = 'CLIENTLANGUAGE';
		this.languageStore = SardegnaForm.createStore(this.languageField);

		this.salutationField = 'SALUTATION';
		this.salutationStore = SardegnaForm.createStore(this.salutationField);

		this.countryField = 'COUNTRY';
		this.countryStore = new Ext.data.JsonStore({
					url : localUrl,
					baseParams : {
						cmd : 'getComboData',
						field : this.countryField
					},
					fields : [{
								name : this.countryField + 'ID',
								type : 'int'
							}, {
								name : this.countryField
							}, {
								name : 'COUNTRYPHONECODE'
							}],
					root : 'data'
				});

		this.titleField = 'TITLE';
		this.titleStore = SardegnaForm.createStoreWithAdditionalValue(
				this.titleField, '');

		var phoneTypeGroup = this.generateContactTypeGroup(2, 'cntFirstPhone',
				1);

		Ext.apply(Ext.form.VTypes, {
					country : function(val, field) {
						if (!field.getValue()) {
							return;
						}
						return (field.getValue() === -1) ? false : true;
					}
				});

		Ext.apply(this, {
			items : [{
						xtype : 'hlabel',
						text : this.translations.personalData
					}, {
						xtype : 'container',
						itemId : 'cntOwnerEmailCheck',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.4
						},
						items : [{
									items : [{
										xtype : 's-textfield',
										fieldLabel : this.translations.email,
										name : 'email',
										vtype : 'email',
										allowBlank : false,
										maxLength : 100,
										width : this.fieldWidth,
										tabIndex : 1
											/*
											 * , listeners : { blur : { fn :
											 * this.onBlurEmail, scope : this } }
											 */
										}]
								}, {
									columnWidth : 0.3,
									items : {
										xtype : 'llabel',
										ctCls : 'label-top-spacer',
										text : this.translations.addEmail,
										listeners : {
											afterrender : {
												fn : function(cmp) {
													cmp.getEl().on({
														click : {
															fn : this.onAddEmail,
															scope : this
														}
													});
												},
												scope : this
											}
										}
									}
								}, {
									columnWidth : 0.3,
									style : 'padding-top: 10px',
									itemId : 'cntEmailCheck'
								}]
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalEmail',
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 'container',
						itemId : 'cntPersonalData',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.5,
							defaults : {
								width : this.fieldWidth
							}
						},
						items : [{
							itemId : 'cntSalutation',
							items : [{
								itemId : 'fldSalutation',
								xtype : 's-combobox',
								fieldLabel : this.translations.salutation,
								mode : 'remote',
								store : this.salutationStore,
								displayField : this.salutationField,
								name : this.salutationField,
								valueField : this.salutationField + 'ID',
								hiddenName : this.salutationField + 'ID',
								allowBlank : false,
								editable : false,
								tabIndex : 100,
								queryParam : 'sprachID',
								listeners : {
									beforequery : {
										fn : function(queryEvent) {
											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntLanguage')
													.getComponent('fldLanguage');
											var val = fld.getValue();
											queryEvent.cancel = (queryEvent.query == val);
											queryEvent.query = val;
										},
										scope : this
									}
								}
							}, {
								xtype : 's-textfield',
								name : 'firstname',
								maxLength : 50,
								allowBlank : false,
								tabIndex : 102,
								fieldLabel : this.translations.firstName
							}, {
								id : 'countryCmb',
								xtype : 's-combobox',
								fieldLabel : this.translations.country,
								mode : 'remote',
								store : this.countryStore,
								displayField : this.countryField,
								valueField : this.countryField + 'ID',
								hiddenName : this.countryField + 'ID',
								allowBlank : false,
								tabIndex : 104,
								listeners : {
									change : {
										fn : this.onCountrySelect,
										scope : this
									}
								},
								vtype : 'country'
							}, {
								xtype : 's-textfield',
								name : 'address',
								maxLength : 50,
								fieldLabel : this.translations.address,
								tabIndex : 106,
								allowBlank : false
							}, {
								xtype : 's-textfield',
								name : 'zipcode',
								maxLength : 50,
								fieldLabel : this.translations.zipcode,
								tabIndex : 108,
								allowBlank : false
							}]
						}, {
							itemId : 'cntLanguage',
							items : [{
								xtype : 's-combobox',
								itemId : 'fldTitle',
								fieldLabel : this.translations.title,
								mode : 'remote',
								store : this.titleStore,
								displayField : this.titleField,
								name : this.titleField,
								valueField : this.titleField + 'ID',
								hiddenName : this.titleField + 'ID',
								tpl : '<tpl for="."><div class="x-combo-list-item">{'
										+ this.titleField
										+ '}<tpl if="xindex === 1">&nbsp;</tpl></div></tpl>',
								editable : false,
								tabIndex : 101,
								queryParam : 'sprachID',
								listeners : {
									beforequery : {
										fn : function(queryEvent) {
											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntLanguage')
													.getComponent('fldLanguage');
											var val = fld.getValue();
											queryEvent.cancel = (queryEvent.query == val);
											queryEvent.query = val;
										},
										scope : this
									}
								}
							}, {
								xtype : 's-textfield',
								name : 'lastname',
								maxLength : 50,
								allowBlank : false,
								tabIndex : 103,
								fieldLabel : this.translations.lastName
							}, {
								itemId : 'fldLanguage',
								xtype : 's-combobox',
								fieldLabel : this.translations.language,
								mode : 'remote',
								store : this.languageStore,
								displayField : this.languageField,
								valueField : this.languageField + 'ID',
								hiddenName : this.languageField + 'ID',
								allowBlank : false,
								tabIndex : 105,
								value : this.defaultLanguage,
								listeners : {
									select : {
										fn : function() {
											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntLanguage')
													.getComponent('fldTitle');
											fld.reset();

											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntSalutation')
													.getComponent('fldSalutation');
											fld.reset();
										},
										scope : this
									}
								}
							}, {
								xtype : 's-textfield',
								name : 'city',
								maxLength : 50,
								tabIndex : 107,
								fieldLabel : this.translations.city,
								allowBlank : false
							}]
						}]
					}, {
						xtype : 'container',
						layout : 'form',
						items : [{
									xtype : 'label',
									text : this.translations.phone,
									style : 'font-size: 11px'
								}, {
									xtype : 'box',
									autoEl : {
										tag : 'span',
										html : '*'
									},
									style : {
										color : '#c90002',
										fontSize : '11px'
									}
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							defaults : {
								xtype : 'label',
								style : 'font-size: 9px'
							}
						},
						items : [{
									columnWidth : 0.075,
									items : [{
												text : this.translations.countryCode
											}]
								}, {
									columnWidth : 0.075,
									items : [{
												text : this.translations.areaCode
											}]
								}, {
									columnWidth : 0.15,
									items : [{
												text : this.translations.phoneNumber
											}]
								}]
					}, {
						itemId : 'cntFirstPhone',
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.5
						},
						items : [{
									columnWidth : 0.075,
									items : [{
												xtype : 's-textfield',
												name : 'phoneCountryCode_1',
												maxLength : 10,
												hideLabel : true,
												width : 38,
												tabIndex : 200
											}, {
												xtype : 'hidden',
												name : 'phoneID_1'
											}]
								}, {
									columnWidth : 0.075,
									items : [{
												xtype : 's-textfield',
												name : 'phonePrefix_1',
												maxLength : 10,
												hideLabel : true,
												width : 38,
												tabIndex : 200,
												allowBlank : false
											}]
								}, {
									columnWidth : 0.15,
									items : [{
												xtype : 's-textfield',
												name : 'phone_1',
												maxLength : 28,
												hideLabel : true,
												width : 83,
												tabIndex : 200,
												allowBlank : false
											}]
								}, {
									columnWidth : 0.6,
									itemId : 'cntFirstPhone1',
									items : [{
												xtype : 'container',
												itemId : 'cntFirstPhone',
												layout : 'form'
											}]
								}, {
									columnWidth : 0.1
								}]
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalPhone',
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalFax',
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalFaxPhoneButtons',
						defaults : {
							xtype : 'container',
							defaults : {
								xtype : 'llabel'
							}
						},
						items : [{
							items : {
								text : this.translations.addPhoneNumber,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
														click : {
															fn : this.onAddPhoneNumber,
															scope : this
														}
													});
										},
										scope : this
									}
								}
							}
						}, {
							itemId : 'cntAdditionalFaxButton',
							items : {
								text : this.translations.addFaxNumber,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
														click : {
															fn : this.onAddFaxNumber,
															scope : this
														}
													});
										},
										scope : this
									}
								}
							}
						}]
					}]
		});
		Ext.ux.PersonalData.superclass.initComponent.apply(this, arguments);
	},
	onAddEmail : function(genHidden) {
		var cnt = this.getComponent('cntAdditionalEmail');
		if (!this.emailCounter)
			this.emailCounter = 1;
		if (cnt) {
			if (cnt.findByType('container').length === 0)
				cnt.add({
							layout : 'form',
							items : [{
										xtype : 'label',
										text : this.translations.additionalEmail,
										style : 'font-size: 11px'
									}]
						});

			var groupCfg = this.generateContactTypeGroup(1,
					'cntAdditionalEmail', this.emailCounter);
			var listItems = [{
						xtype : 's-textfield',
						hideLabel : true,
						maxLength : 100,
						name : 'additionalEmail_' + this.emailCounter,
						width : 225,
						vtype : 'email',
						tabIndex : 1
					}];
			if (genHidden === true)
				listItems.push({
							xtype : 'hidden',
							name : 'additionalEmailID_' + this.emailCounter
						});
			cnt.add({
				itemId : 'cntAdditionalEmail' + this.emailCounter,
				// height : cnt.findByType('container').length ? 30 : 43,
				defaults : {
					xtype : 'container',
					layout : 'form',
					labelAlign : 'top'
				},
				items : [{
							itemId : 'firstCmp',
							columnWidth : 0.4,
							items : listItems
						}, {
							itemId : 'cntAdditionalEmail',
							columnWidth : 0.5,
							items : groupCfg
						}, {
							columnWidth : 0.1,
							items : [{
								xtype : 'llabel',
								text : this.translations.remove,
								ctCls : cnt.findByType('container').length
										? ''
										: 'label-top-spacer',
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
												click : {
													fn : function(ev, html,
															options) {
														var owner = cmp.ownerCt.ownerCt.ownerCt;
														var arr = cmp.ownerCt.ownerCt
																.getComponent('firstCmp')
																.findByType('hidden');
														var hidden = arr
																&& arr.length
																? arr[0]
																: null;
														// console.log(hidden
														// .getValue());
														if (hidden
																&& hidden
																		.getValue())
															owner.ownerCt
																	.addContactToDelete(hidden
																			.getValue());
														owner
																.remove(
																		cmp.ownerCt.ownerCt,
																		true);
														if (owner
																.findByType('container').length === 1)
															owner
																	.removeAll(true);
														owner.doLayout();
													},
													scope : cmp
												}
											});
										},
										scope : this
									}
								}
							}]
						}]
			});
			cnt.doLayout();
			// this.getForm().setValues(this.loadedData);
			this.emailCounter++;
		}
	},
	onAddFaxNumber : function(genHidden) {
		var cnt = this.getComponent('cntAdditionalFax');
		var counter = 1;
		if (cnt && cnt.findByType('container').length === 0) {
			this.showFaxButton(false);
			cnt.add({
						layout : 'form',
						items : [{
									xtype : 'label',
									text : this.translations.fax,
									style : 'font-size: 11px'
								}]
					});
			var groupCfg = this.generateContactTypeGroup(3, 'cntAdditionalFax',
					counter);
			var listItems = [{
				xtype : 's-textfield',
				hideLabel : true,
				maxLength : 10,
				name : 'faxCountryCode_1',
				value : this
						.getCountryCode(Ext.getCmp('countryCmb').getValue()),
				tabIndex : 300,
				width : 38
			}];
			if (genHidden === true)
				listItems.push({
							xtype : 'hidden',
							name : 'faxID_' + counter
						});
			cnt.add({
				itemId : 'cntAdditionalFax' + counter,
				// height : 40,
				defaults : {
					xtype : 'container',
					layout : 'form',
					labelAlign : 'top'
				},
				items : [{
							itemId : 'firstCmp',
							columnWidth : 0.075,
							items : listItems
						}, {
							columnWidth : 0.075,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 10,
										name : 'faxPrefix_1',
										tabIndex : 300,
										width : 38
									}]
						}, {
							columnWidth : 0.15,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 28,
										name : 'fax_1',
										tabIndex : 300,
										width : 83
									}]
						}, {
							itemId : 'cntAdditionalFax',
							columnWidth : 0.6,
							items : groupCfg
						}, {
							columnWidth : 0.1,
							items : [{
								xtype : 'llabel',
								text : this.translations.remove,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
												click : {
													fn : function(ev, html,
															options) {
														var owner = cmp.ownerCt.ownerCt.ownerCt;
														var arr = cmp.ownerCt.ownerCt
																.getComponent('firstCmp')
																.findByType('hidden');
														var hidden = arr
																&& arr.length
																? arr[0]
																: null;
														// .getComponent('hiddenID');
														// console.log(hidden.getValue());
														if (hidden
																&& hidden
																		.getValue())
															owner.ownerCt
																	.addContactToDelete(hidden
																			.getValue());
														/*
														 * owner .remove(
														 * cmp.ownerCt.ownerCt,
														 * true);
														 */
														owner.removeAll(true);
														owner.doLayout();
													},
													scope : cmp
												}
											});
										},
										scope : this
									}
								}
							}]
						}],
				listeners : {
					destroy : function() {
						this.showFaxButton(true);
					},
					scope : this
				}
			});
			cnt.doLayout();
			// this.getForm().setValues(this.loadedData);
		}
	},
	onAddPhoneNumber : function(genHidden) {
		var cnt = this.getComponent('cntAdditionalPhone');
		if (!this.phoneCounter)
			this.phoneCounter = 2;
		if (cnt) {
			var groupCfg = this.generateContactTypeGroup(2,
					'cntAdditionalPhone', this.phoneCounter);

			var listItems = [{
				xtype : 's-textfield',
				hideLabel : true,
				maxLength : 10,
				name : 'phoneCountryCode_' + this.phoneCounter,
				width : 38,
				value : this
						.getCountryCode(Ext.getCmp('countryCmb').getValue()),
				tabIndex : 200
			}];
			if (genHidden === true)
				listItems.push({
							xtype : 'hidden',
							name : 'phoneID_' + this.phoneCounter
						});
			cnt.add({
				itemId : 'cntAdditionalPhone' + this.phoneCounter,
				// height : 30,
				defaults : {
					xtype : 'container',
					layout : 'form',
					labelAlign : 'top'
				},
				items : [{
							itemId : 'firstCmp',
							columnWidth : .075,
							items : listItems
						}, {
							columnWidth : .075,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 10,
										name : 'phonePrefix_'
												+ this.phoneCounter,
										width : 38,
										tabIndex : 200
									}]
						}, {
							columnWidth : 0.15,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 28,
										name : 'phone_' + this.phoneCounter,
										width : 83,
										tabIndex : 200
									}]
						}, {
							columnWidth : 0.6,
							itemId : 'cntAdditionalPhone',
							items : groupCfg
						}, {
							style : {
								paddingTop : '6px'
							},
							columnWidth : 0.1,
							items : [{
								xtype : 'llabel',
								text : this.translations.remove,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
												click : {
													fn : function(ev, html,
															options) {
														var owner = cmp.ownerCt.ownerCt.ownerCt;
														var arr = cmp.ownerCt.ownerCt
																.getComponent('firstCmp')
																.findByType('hidden');
														var hidden = arr
																&& arr.length
																? arr[0]
																: null;
														// console.log(hidden
														// .getValue());
														if (hidden
																&& hidden
																		.getValue())
															owner.ownerCt
																	.addContactToDelete(hidden
																			.getValue());

														owner
																.remove(
																		cmp.ownerCt.ownerCt,
																		true);
														owner.doLayout();
													},
													scope : cmp
												}
											});
										},
										scope : this
									}
								}
							}]
						}]
			});
			cnt.doLayout();
			this.phoneCounter++;
		}
	},
	generateContactTypeGroup : function(contactType, container, index) {
		var result = [];
		var generateName = function(tt, ii) {
			var type = 'phone';
			switch (tt) {
				case 1 :
					type = 'additionalEmail';
					break;
				case 2 :
					type = 'phone';
					break;
				case 3 :
					type = 'fax';
			}
			return String.format('{0}Type_{1}', type, ii);
		};
		var generateGroupName = function(tt, ii) {
			var type = 'phone';
			switch (tt) {
				case 1 :
					type = 'additionalEmail';
					break;
				case 2 :
					type = 'phone';
					break;
				case 3 :
					type = 'fax';
			}
			return String.format('group{0}{1}', type, ii);
		};
		var generateTabIndex = function(tt) {
			var tb = 1;
			switch (tt) {
				case 1 :
					tb = 1;
					break;
				case 2 :
					tb = 200;
					break;
				case 3 :
					tb = 300;
			}
			return tb;
		};

		if (!this.contactGroups)
			this.contactGroups = {};
		if (this.contactGroups['group' + contactType]) {
			var o = this.contactGroups['group' + contactType];
			for (var i = 0, len = o.items.length; i < len; i++)
				Ext.apply(o.items[i], {
							name : generateName(contactType, index),
							tabIndex : generateTabIndex(contactType)
						});
			result = [o];
		} else {
			new Ext.data.JsonStore({
				url : this.url,
				cnt : container,
				idx : index,
				baseParams : {
					cmd : 'getContactTypes',
					type : contactType
				},
				fields : [{
							name : 'boxLabel'
						}, {
							name : 'inputValue'
						}],
				root : 'data',
				idProperty : 'inputValue',
				autoLoad : true,
				listeners : {
					'load' : {
						fn : function(store, records, options) {
							// this.itemLoaded();
							var checkboxItems = [];
							var counter = 0;
							Ext.each(records, function(record, idx, all) {
										checkboxItems[counter] = record.data;
										Ext.apply(checkboxItems[counter], {
													name : generateName(
															store.baseParams.type,
															store.idx),
													checked : counter === 0,
													inputValue : ''
															+ record.data.inputValue
												});
										counter++;
									});
							this.contactGroups['group' + store.baseParams.type] = {
								xtype : 'radiogroup',
								name : generateGroupName(store.baseParams.type,
										store.idx),
								hideLabel : true,
								items : checkboxItems,
								columns : 3,
								tabIndex : generateTabIndex(contactType)
							};

							var cnt = this.getComponent(store.cnt)
									.getComponent(store.cnt + store.idx)
									.getComponent(store.cnt);

							if (Ext.isIE6) {
								var o = this.contactGroups['group'
										+ store.baseParams.type];
								Ext.apply(o, {
											width : cnt.getWidth()
										});
								cnt.add(o);
							} else {
								cnt.add(this.contactGroups['group'
										+ store.baseParams.type]);
							}

							cnt.doLayout();
							this.itemLoaded();
							// this.getForm().setValues(this.loadedData);
						},
						scope : this
					}
				}
			});
		}
		return result;
	},
	getCountryCode : function(countryID) {
		var s = this.countryStore;
		var idx = s.find(this.countryField + 'ID', countryID);
		if (idx >= 0) {
			var rec = s.getAt(idx);
			if (rec)
				return rec.get('COUNTRYPHONECODE');
		}
		return '';
	},
	showFaxButton : function(show) {
		var faxButton = this.getComponent('cntAdditionalFaxPhoneButtons')
				.getComponent('cntAdditionalFaxButton');
		if (faxButton) {
			if (show)
				faxButton.show();
			else
				faxButton.hide();
		}
	},
	appendContactData : function(emailsCount, phonesCount, faxCount) {
		for (var i = 0; i < phonesCount; i++)
			this.onAddPhoneNumber(true);

		for (var i = 0; i < faxCount; i++)
			this.onAddFaxNumber(true);
		if (faxCount > 0)
			this.itemsToLoad++;

		for (var i = 0; i < emailsCount; i++)
			this.onAddEmail(true);
		if (emailsCount > 0)
			this.itemsToLoad++;
	},
	itemLoaded : function() {
		this.itemsToLoad--;
		if (this.itemsToLoad <= 0)
			this.fireEvent('readyForUpdate');
	},
	getContactsToDelete : function() {
		return this.contactsToDelete;
	},
	addContactToDelete : function(contact) {
		if (!this.contactsToDelete)
			this.contactsToDelete = '' + contact;
		else
			this.contactsToDelete += ',' + contact;
	},
	onCountrySelect : function(combo, newVal, oldVal) {
		
	}
});

Ext.reg('s-personal-data', Ext.ux.PersonalData);
Ext.ns('Ext.ux');

Ext.ux.AdditionalWishlistObjects = Ext.extend(Ext.Container, {
	translations: null,
	objectType: 'villa',
	objectList: null,
	initComponent : function() {
		Ext.apply(this, {
			items: [{
				xtype: 'checkbox',
				name: this.objectType + 'FromWishlist',
				hideLabel: true,				
				boxLabel: this.translations && this.objectType && this.translations[this.objectType+'FromWishlist'] ? 
							this.translations[this.objectType+'FromWishlist'] : 
							'missing translation',
				hidden: true
			}]
		});	
	
		if (this.url && this.checkObjects) {
			Ext.Ajax.request({
				url : this.url,
				success : this.onHasObjectsOnWishlist,
				scope : this,
				params : {
					cmd : 'hasObjectsOnWishlist',
					type : this.objectType,
					list : this.objectList.join(',')
				}
			});
		}
	
		Ext.ux.AdditionalWishlistObjects.superclass.initComponent.apply(this, arguments);
	},
	onHasObjectsOnWishlist: function(response, result) {
		var result = Ext.decode(response.responseText, true);
		if (result && result.hasObjects) {
			this.items.items[0].setVisible(true);
		}
	}
});

Ext.reg('s-additional-wishlist-objects', Ext.ux.AdditionalWishlistObjects);Ext.ns('Ext.ux');

Ext.ux.RequestHolidayRental = Ext.extend(Ext.ux.SardegnaForm, {
	translations : {
		personalData : 'Personal Data',
		email : 'Your Email',
		salutation : 'Salutation',
		country : 'Country',
		title : 'Title',
		firstName : 'First Name',
		lastName : 'Last Name',
		language : 'Language',
		phone : 'Phone',
		privatePhone : 'private',
		businessPhone : 'business',
		mobilePhone : 'mobile',
		addPhoneNumber : 'Add Phone Number',
		addFaxNumber : 'Add Fax Number',
		addEmail : 'Add Email Address',
		travelPlans : 'Travel Plans',
		arrivalDate : 'Arrival as soon as',
		departureDate : 'Departure as late as',
		days : 'How long will you stay?',
		adults : 'Adults',
		children : 'Children',
		pet : 'I am traveling with a pet',
		region : 'Region',
		northern : 'Northern',
		southern : 'Southern',
		eastern : 'Eastern',
		western : 'Western',
		any : 'any',
		distanceToSea : 'Distance to the sea',
		anyDistance : 'Any distance',
		to150 : 'First Series',
		to400 : 'Reachable on foot',
		over400 : 'Accessible by car',
		offerForVillas : 'I want an offer for villas',
		bedrooms : 'Bedrooms min.',
		bathrooms : 'Bathrooms min.',
		facilities : 'Facilities',
		pool : 'Pool',
		maxVillaCosts : 'Including additional expenses the house may cost',
		offerForHotels : 'I want an offer for hotels',
		flexibility : 'Flexibility',
		flexible : 'my dates are flexible',
		fixed : 'my dates are fixed',
		stars : 'Stars',
		hotelSize : 'Hotel size',
		forChildren : 'For Children',
		setBed : 'Additional bed',
		seperateRoom : 'Seperate room',
		board : 'Board',
		withoutFood : 'none',
		breakfast : 'breakfast',
		halfBoard : 'half-board',
		fullBoard : 'full-board',
		maxHotelCosts : 'The hotel may cost per night and person',
		offerForPlane : 'I want an offer for planes',
		planeFrom : 'From',
		planeTo : 'To',
		travelerFirstName : 'First name',
		travelerLastName : 'Last name',
		travelerFullName : 'Traveler\'s full name',
		travelerBirthDate : 'Date of birth',
		addTraveler : 'Add Traveler',
		offerForCar : 'I want an offer for rental cars',
		carClass : 'Car class',
		offerForFerries : 'I want an offer for ferries',
		specialDesires : 'Do you have special desires?',
		howFound : 'How did you find us?',
		requestOffer : 'Request offer',
		child : 'Child',
		rooms : 'Rooms',
		fax : 'Fax number',
		remove : 'Remove',
		additionalEmail : 'Additional email',
		childrenAge : 'Age of children at date of travel',
		checkingEmail : 'Checking email...',
		datesOfTravel : 'Dates of travel',
		participants : 'Participants',
		petDesc : 'Animal type and size',
		outgoing : 'Outgoing',
		returnTx : 'Return',
		carType : 'Car type',
		carMake : 'Car make',
		carLength : 'Car length',
		carWidth : 'Car width',
		carHeight : 'Car height',
		ferryRoute : 'Route',
		cabinType : 'Cabin type',
		pickup : 'Pickup',
		dropoff : 'Drop Off',
		driversAge : 'Driver\'s age (at time of travel)',
		driversLicense : 'Driver\'s license valid (at time of travel)',
		driversLicense3more : 'for more then 3 years',
		driversLicense3less : 'for less then 3 years',
		address : 'Address',
		zipcode : 'Zip',
		city : 'City',
		doesnotmatter : 'Does not matter',
		selectDates : 'Select travel dates first',
		importantForHotel : 'What is most important for your hotel?',
		importantForVilla : 'What is most important for your vacation rental?',
		withDeductible : 'with deductible',
		withoutDeductible : 'without deductible',
		ferryOutgoing : 'Outgoing',
		ferryReturn : 'Return',
		pleaseWait : 'Please wait...',
		countryCode : 'Country code',
		areaCode : 'Area code',
		phoneNumber : 'Phone number',
		upTo : 'Up to',
		moreThan : 'More than',
		hotelSeasonInfo : 'This hotel is not open during your selected travel dates. Please enter a date between',
		and : 'and',
		roomCategory : 'Room category',
		roomCategoryEmpty : 'Please select board option first.',
		priceFrom : 'price from',
		euroPersonDay : 'Euro/Person/Day',
		selectOffer : 'Please select what you would like to request.',
		hotelClosed : 'Hotel closed during the selected travel dates.',
		selectAtLeastOneItem : 'You must select at least one item in this group',
		villaFromWishlist : 'Please offer me villas I have on my wishlist',
		hotelFromWishlist : 'Please offer me hotels I have on my wishlist',
		hotelIsAvailable : 'Hotel is available from',
		availableTo : '[date] to [date]',
		subjectToChanges : 'Subject to changes as pricelist for',
		notYetAvailable : 'is not yet available',
		minDateText : 'The date in this field must be equal to or after'
	},
	funnels : null,
	stateful : true,
	stateId : 'sardegna-request-form-state',
	stateEvents : ['saveState'],
	getState : function() {
		var stateToSave = this.valuesForStateSave;
		var state = {};

		if (stateToSave.withPet)
			state['withPet'] = true;

		var fieldsList = ['arrivalDate', 'departureDate', 'adultsCount',
				'childrenCount', 'daysCount', 'petDescription', 'childrenages'];

		for (var i = 0, len = fieldsList.length; i < len; i++) {
			state[fieldsList[i]] = stateToSave[fieldsList[i]];
		}

		state['flexibleDatesGroup'] = String.format('{0},{0}',
				stateToSave.flexibleDates)

		var regions = {};
		for (var i = 0, len = stateToSave.regionData.length; i < len; i++)
			regions[String.format('region-option-{0}',
					stateToSave.regionData[i])] = true;
		state['regionGroup'] = regions;

		return state;
	},
	applyState : function(savedState) {
		this.savedState = savedState;
	},
	createItems : function() {
		// console.log(this.expandItems);

		this.itemsToLoad = 2;

		var showVillas = false;
		var showHotels = false;
		var showPlanes = false;
		var showCars = false;
		var showFerries = false;

		if (this.expandItems) {
			if (this.expandItems.show) {
				var shows = this.expandItems.show.toLowerCase().split(',');
				for (s in shows) {
					if (shows[s] === 'villas')
						showVillas = true;
					else if (shows[s] === 'hotels')
						showHotels = true;
					else if (shows[s] === 'planes')
						showPlanes = true;
					else if (shows[s] === 'cars')
						showCars = true;
					else if (shows[s] === 'ferries')
						showFerries = true;
				}
			}
			this.funnels = this.expandItems;
		}

		if (this.funnels && this.funnels.gf && GLOBAL && GLOBAL.funnels) {
			for (fn in GLOBAL.funnels) {
				if (String.format('{0}Request', this.funnels.gf) == fn) {
					for (var i = 0, len = GLOBAL.googleCodes.length; i < len; i++) {
						try {
							var pageTracker = _gat
									._getTracker(GLOBAL.googleCodes[i]);
							pageTracker._trackPageview(GLOBAL.funnels[fn]);
							if (console) {
								try {
									console.log("tracker: "
											+ GLOBAL.googleCodes[i]
											+ "      funnel: "
											+ GLOBAL.funnels[fn]);
								} catch (ex) {
								}
							}
						} catch (ex) {
						}
					}
				}
			}
		}

		var localUrl = this.url;
		var createStore = function(field) {
			return new Ext.data.JsonStore({
						url : localUrl,
						baseParams : {
							cmd : 'getComboData',
							field : field
						},
						fields : [{
									name : field + 'ID',
									type : 'int'
								}, {
									name : field
								}],
						root : 'data'
					})
		};

		this.languageField = 'CLIENTLANGUAGE';
		this.languageStore = createStore(this.languageField);

		this.salutationField = 'SALUTATION';
		this.salutationStore = createStore(this.salutationField);

		this.airportField = 'AIRPORT';
		this.airportStore = new Ext.data.JsonStore({
					url : localUrl,
					baseParams : {
						cmd : 'getComboData',
						field : this.airportField
					},
					fields : [{
								name : this.airportField + 'ID',
								type : 'int'
							}, {
								name : this.airportField
							}, {
								name : 'COUNTRYNAME'
							}],
					root : 'data'
				});

		this.airportSardegnaField = 'AIRPORTSARDEGNA';
		this.airportSardegnaStore = createStore(this.airportSardegnaField);

		this.rentalcarStationField = 'RENTALCARSTATION';
		this.rentalcarStationStore = createStore(this.rentalcarStationField);

		this.countryField = 'COUNTRY';
		this.countryStore = new Ext.data.JsonStore({
					url : localUrl,
					baseParams : {
						cmd : 'getComboData',
						field : this.countryField
					},
					fields : [{
								name : this.countryField + 'ID',
								type : 'int'
							}, {
								name : this.countryField
							}, {
								name : 'COUNTRYPHONECODE'
							}],
					root : 'data'
				});

		this.hotelSizeField = 'HOTELSIZE';
		this.hotelSizeStore = createStore(this.hotelSizeField);

		this.carclassField = 'CARCLASS';
		this.carclassStore = createStore(this.carclassField);

		this.ferryRouteField = 'FERRYROUTE';
		this.ferryRouteStore = createStore(this.ferryRouteField);

		this.ferryRouteFieldSardegna = 'FERRYROUTESARDEGNA';
		this.ferryRouteStoreSardegna = createStore(this.ferryRouteFieldSardegna);

		this.cabintypeField = 'CABINTYPE';
		this.cabintypeStore = createStore(this.cabintypeField);

		this.cartypeField = 'CARTYPE';
		this.cartypeStore = createStore(this.cartypeField);

		this.howfoundField = 'HOWFOUND';
		this.howfoundStore = createStore(this.howfoundField);

		this.roomCategoryField = "roomCategory";
		this.roomCategoryStore = new Ext.data.JsonStore({
					url : localUrl,
					baseParams : {
						cmd : 'getRoomCategories'
					},
					fields : [{
								name : this.roomCategoryField + 'ID',
								type : 'int'
							}, {
								name : this.roomCategoryField
							}, {
								name : 'roomPrice',
								type : 'float'
							}],
					root : 'data'
				});

		var createStoreWithAdditionalValue = function(field, value) {
			var record = Ext.data.Record.create([{
						name : field + 'ID',
						type : 'int'
					}, {
						name : field
					}]);
			return new Ext.data.JsonStore({
						url : localUrl,
						baseParams : {
							cmd : 'getComboData',
							field : field
						},
						recordDef : record,
						fields : record,
						fieldName : field,
						addValue : value,
						root : 'data',
						listeners : {
							'load' : function(store, records, options) {
								var o = {};
								o[store.fieldName + 'ID'] = 0;
								o[store.fieldName] = store.addValue;
								store.insert(0, new store.recordDef(o));
							}
						}
					});
		};

		this.hotelStarField = 'HOTELSTAR';
		this.hotelStarStore = createStoreWithAdditionalValue(
				this.hotelStarField, this.translations.any);

		this.titleField = 'TITLE';
		this.titleStore = createStoreWithAdditionalValue(this.titleField, '');

		this.maxPriceHotelField = 'MAXPRICEHOTEL';
		this.maxPriceHotelStore = createStoreWithAdditionalValue(
				this.maxPriceHotelField, this.translations.doesnotmatter);

		this.maxPriceVillaField = 'range';
		this.maxPriceVillaRecord = Ext.data.Record.create([{
					name : this.maxPriceVillaField + 'ID',
					type : 'int'
				}, {
					name : this.maxPriceVillaField
				}]);
		this.maxPriceVillaStore = new Ext.data.JsonStore({
					url : localUrl,
					baseParams : {
						cmd : 'getVillaPriceRanges',
						arrivalDate : new Date()
					},
					recordDef : this.maxPriceVillaRecord,
					fields : this.maxPriceVillaRecord,
					fieldName : this.maxPriceVillaField,
					addValue : this.translations.doesnotmatter,
					root : 'data'/*
									 * , listeners : { 'load' : function(store,
									 * records, options) { var o = {};
									 * o[store.fieldName + 'ID'] = 0;
									 * o[store.fieldName] = store.addValue;
									 * store.insert(0, new store.recordDef(o)); } }
									 */
				});

		this.generateArray = function(to, from) {
			var result = [];
			for (var i = from || 0; i <= to; i++) {
				result.push([i]);
			}
			return result;
		}

		this.daysStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'days',
								type : 'int'
							}],
					data : this.generateArray(42, 1)
				});
		this.adultsStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'adults',
								type : 'int'
							}],
					data : this.generateArray(12, 1)
				});
		this.childrenStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'children',
								type : 'int'
							}],
					data : this.generateArray(8)
				});
		this.bedroomsStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'bedrooms',
								type : 'int'
							}],
					data : this.generateArray(8, 1)
				});
		this.bathroomsStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'bathrooms',
								type : 'int'
							}],
					data : this.generateArray(8, 1)
				});

		this.regionsStore = new Ext.data.JsonStore({
			url : this.url,
			baseParams : {
				cmd : 'getRegionCheckboxes'
			},
			fields : [{
						name : 'boxLabel'
					}, {
						name : 'inputValue'
					}],
			root : 'data',
			idProperty : 'inputValue',
			// autoLoad : true,
			listeners : {
				'load' : {
					fn : function(store, records, options) {
						var checkboxItems = [];

						checkboxItems[0] = {
							// xtype : 'radio',
							name : 'region',
							actAsRadio : true,
							hideLabel : true,
							boxLabel : this.translations.any,
							checked : true,
							inputValue : this.translations.any,
							valueID : '0'
						};
						var counter = 1;
						Ext.each(records, function(record, idx, all) {
									checkboxItems[counter] = record.data;
									Ext.apply(checkboxItems[counter], {
												name : 'region',
												id : 'region-option-'
														+ record.data.inputValue,
												inputValue : record.data.boxLabel,
												valueID : record.data.inputValue
											});
									counter++;
								});
						var owner = this.getComponent('cntRegion');
						var cnt = owner.getComponent('cntRegionGroup');
						if (cnt) {
							cnt.add({
										xtype : 'checkboxgroup',
										id : 'regionGroup',
										hideLabel : true,
										allowBlank : false,
										style : 'padding-top: 14px',
										defaults : {
											actAsRadio : false,
											groupID : 'regionGroup',
											listeners : {
												check : {
													fn : this.onCheckOption,
													scope : this
												}
											}
										},
										items : checkboxItems,
										columns : 3,
										tabIndex : 700
									});
							cnt.doLayout();
							this.fireEvent('regionsLoaded');
						}
					},
					scope : this
				}
			}
		});

		this.hasOneHotel = this.expandItems && this.expandItems.hotelID
				&& this.expandItems.hotelID.split(',').length === 1;

		this.hotelsList = this.expandItems && this.expandItems.hotelID
				? this.expandItems.hotelID.split(',')
				: [];

		this.villasList = this.expandItems && this.expandItems.villaID
				? this.expandItems.villaID.split(',')
				: [];

		Ext.apply(Ext.form.VTypes, {
			daterange : function(val, field) {
				var date = field.parseDate(val);

				if (!date) {
					return true;
				}
				if (field.startDateField
						&& (!this.dateRangeMax || (date.getTime() != this.dateRangeMax
								.getTime()))) {
					var start = Ext.getCmp(field.startDateField);
					start.setMaxValue(date);
					// start.validate();
					this.dateRangeMax = date;
				} else if (field.endDateField
						&& (!this.dateRangeMin || (date.getTime() != this.dateRangeMin
								.getTime()))) {
					var end = Ext.getCmp(field.endDateField);
					end.setMinValue(date);
					// end.validate();
					this.dateRangeMin = date;
				}
				return true;
			},
			country : function(val, field) {
				if (!field.getValue()) {
					return;
				}
				return (field.getValue() === -1) ? false : true;
			}
		});

		var width1 = 225;
		var phoneTypeGroup = this.generateContactTypeGroup(2, 'cntFirstPhone',
				1);
		Ext.apply(this, {
			items : [{
						xtype : 's-spacer'
					}, {
						xtype : 'hlabel',
						text : this.translations.personalData
					}, {
						xtype : 'container',
						itemId : 'cntOwnerEmailCheck',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.4
						},
						items : [{
									items : [{
												xtype : 's-textfield',
												fieldLabel : this.translations.email,
												name : 'email',
												vtype : 'email',
												allowBlank : false,
												maxLength : 100,
												width : width1,
												tabIndex : 1,
												listeners : {
													blur : {
														fn : this.onBlurEmail,
														scope : this
													}
												}
											}]
								}, {
									columnWidth : 0.3,
									items : {
										xtype : 'llabel',
										ctCls : 'label-top-spacer',
										text : this.translations.addEmail,
										listeners : {
											afterrender : {
												fn : function(cmp) {
													cmp.getEl().on({
														click : {
															fn : this.onAddEmail,
															scope : this
														}
													});
												},
												scope : this
											}
										}
									}
								}, {
									columnWidth : 0.3,
									style : 'padding-top: 10px',
									itemId : 'cntEmailCheck'
								}]
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalEmail',
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 'container',
						itemId : 'cntPersonalData',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.5,
							defaults : {
								width : width1
							}
						},
						items : [{
							itemId : 'cntSalutation',
							items : [{
								itemId : 'fldSalutation',
								xtype : 's-combobox',
								fieldLabel : this.translations.salutation,
								mode : 'remote',
								store : this.salutationStore,
								displayField : this.salutationField,
								name : this.salutationField,
								valueField : this.salutationField + 'ID',
								hiddenName : this.salutationField + 'ID',
								allowBlank : false,
								editable : false,
								tabIndex : 100,
								queryParam : 'sprachID',
								listeners : {
									beforequery : {
										fn : function(queryEvent) {
											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntLanguage')
													.getComponent('fldLanguage');
											var val = fld.getValue();
											queryEvent.cancel = (queryEvent.query == val);
											queryEvent.query = val;
										},
										scope : this
									}
								}
							}, {
								xtype : 's-textfield',
								name : 'firstname',
								maxLength : 50,
								allowBlank : false,
								tabIndex : 102,
								fieldLabel : this.translations.firstName
							}, {
								id : 'countryCmb',
								xtype : 's-combobox',
								fieldLabel : this.translations.country,
								mode : 'remote',
								store : this.countryStore,
								displayField : this.countryField,
								valueField : this.countryField + 'ID',
								hiddenName : this.countryField + 'ID',
								allowBlank : false,
								tabIndex : 104,
								listeners : {
									change : {
										fn : this.onCountrySelect,
										scope : this
									}
								},
								vtype : 'country'
							}, {
								xtype : 's-textfield',
								name : 'address',
								maxLength : 50,
								fieldLabel : this.translations.address,
								tabIndex : 106
							}, {
								xtype : 's-textfield',
								name : 'zipcode',
								maxLength : 50,
								fieldLabel : this.translations.zipcode,
								tabIndex : 108
							}]
						}, {
							itemId : 'cntLanguage',
							items : [{
								xtype : 's-combobox',
								itemId : 'fldTitle',
								fieldLabel : this.translations.title,
								mode : 'remote',
								store : this.titleStore,
								displayField : this.titleField,
								name : this.titleField,
								valueField : this.titleField + 'ID',
								hiddenName : this.titleField + 'ID',
								tpl : '<tpl for="."><div class="x-combo-list-item">{'
										+ this.titleField
										+ '}<tpl if="xindex === 1">&nbsp;</tpl></div></tpl>',
								editable : false,
								tabIndex : 101,
								queryParam : 'sprachID',
								listeners : {
									beforequery : {
										fn : function(queryEvent) {
											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntLanguage')
													.getComponent('fldLanguage');
											var val = fld.getValue();
											queryEvent.cancel = (queryEvent.query == val);
											queryEvent.query = val;
										},
										scope : this
									}
								}
							}, {
								xtype : 's-textfield',
								name : 'lastname',
								maxLength : 50,
								allowBlank : false,
								tabIndex : 103,
								fieldLabel : this.translations.lastName
							}, {
								itemId : 'fldLanguage',
								xtype : 's-combobox',
								fieldLabel : this.translations.language,
								mode : 'remote',
								store : this.languageStore,
								displayField : this.languageField,
								valueField : this.languageField + 'ID',
								hiddenName : this.languageField + 'ID',
								allowBlank : false,
								tabIndex : 105,
								value : this.defaultLanguage,
								listeners : {
									select : {
										fn : function() {
											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntLanguage')
													.getComponent('fldTitle');
											fld.reset();

											var fld = this
													.getComponent('cntPersonalData')
													.getComponent('cntSalutation')
													.getComponent('fldSalutation');
											fld.reset();
										},
										scope : this
									}
								}
							}, {
								xtype : 's-textfield',
								name : 'city',
								maxLength : 50,
								tabIndex : 107,
								fieldLabel : this.translations.city
							}]
						}]
					}, {
						xtype : 'container',
						layout : 'form',
						items : [{
									xtype : 'label',
									text : this.translations.phone,
									style : 'font-size: 11px'
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							defaults : {
								xtype : 'label',
								style : 'font-size: 9px'
							}
						},
						items : [{
									columnWidth : 0.075,
									items : [{
												text : this.translations.countryCode
											}]
								}, {
									columnWidth : 0.075,
									items : [{
												text : this.translations.areaCode
											}]
								}, {
									columnWidth : 0.15,
									items : [{
												text : this.translations.phoneNumber
											}]
								}]
					}, {
						itemId : 'cntFirstPhone',
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.5
						},
						items : [{
									columnWidth : 0.075,
									items : [{
												xtype : 's-textfield',
												name : 'phoneCountryCode_1',
												maxLength : 10,
												hideLabel : true,
												width : 38,
												tabIndex : 200
											}, {
												xtype : 'hidden',
												name : 'phoneID_1'
											}]
								}, {
									columnWidth : 0.075,
									items : [{
												xtype : 's-textfield',
												name : 'phonePrefix_1',
												maxLength : 10,
												hideLabel : true,
												width : 38,
												tabIndex : 200
											}]
								}, {
									columnWidth : 0.15,
									items : [{
												xtype : 's-textfield',
												name : 'phone_1',
												maxLength : 28,
												hideLabel : true,
												width : 83,
												tabIndex : 200
											}]
								}, {
									columnWidth : 0.6,
									itemId : 'cntFirstPhone1',
									items : [{
												xtype : 'container',
												itemId : 'cntFirstPhone',
												layout : 'form'
											}]
								}, {
									columnWidth : 0.1
								}]
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalPhone',
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalFax',
						defaults : {
							xtype : 'container',
							layout : 'column'
						}
					}, {
						xtype : 'container',
						itemId : 'cntAdditionalFaxPhoneButtons',
						defaults : {
							xtype : 'container',
							defaults : {
								xtype : 'llabel'
							}
						},
						items : [{
							items : {
								text : this.translations.addPhoneNumber,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
														click : {
															fn : this.onAddPhoneNumber,
															scope : this
														}
													});
										},
										scope : this
									}
								}
							}
						}, {
							itemId : 'cntAdditionalFaxButton',
							items : {
								text : this.translations.addFaxNumber,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
														click : {
															fn : this.onAddFaxNumber,
															scope : this
														}
													});
										},
										scope : this
									}
								}
							}
						}]
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 'hlabel',
						text : this.translations.travelPlans
					}, {
						xtype : 'label',
						text : this.translations.flexibility
					}, {
						xtype : 'radiogroup',
						columns : 3,
						hideLabel : true,
						tabIndex : 600,
						name : 'flexibleDatesGroup',
						items : [{
									boxLabel : this.translations.flexible,
									checked : true,
									name : 'flexibleDates',
									inputValue : 'yes'
								}, {
									boxLabel : this.translations.fixed,
									name : 'flexibleDates',
									inputValue : 'no'
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.33
						},
						items : [{
									items : [{
												xtype : 'label',
												text : this.translations.datesOfTravel
											}]
								}, {
									items : [{
												xtype : 'label',
												text : this.translations.participants
											}]
								}, {

								}]
					}, {
						xtype : 'container',
						itemId : 'cntParticipants',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : 0.33
						},
						items : [{
							itemId : 'cntTravelDates',
							items : [{
										itemId : 'fldArrivalDate',
										xtype : 's-datefield',
										fieldLabel : this.translations.arrivalDate,
										// vtype : 'daterange',
										id : 'arrivalDate',
										name : 'arrivalDate',
										editable : true,
										endDateField : 'departureDate',
										tabIndex : 601,
										listeners : {
											change : {
												fn : function(fld, newVal,
														oldVal) {
													this.enableVillaPrices();
													this.updateHotelsData();
												},
												scope : this
											}
										}
									}, {
										itemId : 'fldDepartureDate',
										xtype : 's-datefield',
										fieldLabel : this.translations.departureDate,
										// vtype : 'daterange',
										id : 'departureDate',
										name : 'departureDate',
										editable : true,
										startDateField : 'arrivalDate',
										tabIndex : 604,
										listeners : {
											change : function() {
												this.updateHotelsData();
											},
											scope : this
										}
									}]
						}, {
							items : [{
										xtype : 's-combobox',
										name : 'adultsCount',
										fieldLabel : this.translations.adults,
										mode : 'local',
										store : this.adultsStore,
										displayField : 'adults',
										allowBlank : false,
										tabIndex : 602,
										listeners : {
											select : {
												fn : this.onAdultsSelect,
												scope : this
											}
										},
										width : 78
									}, {
										xtype : 's-combobox',
										name : 'childrenCount',
										fieldLabel : this.translations.children,
										mode : 'local',
										store : this.childrenStore,
										displayField : 'children',
										allowBlank : false,
										tabIndex : 605,
										listeners : {
											select : this.onChildrenSelect,
											// change : this.onChildrenSelect,
											scope : this
										},
										width : 78
									}]
						}, {
							itemId : 'cntPetDescription',
							items : [{
										xtype : 'checkbox',
										name : 'withPet',
										boxLabel : this.translations.pet,
										fieldLabel : '',
										inputValue : 'yes',
										tabIndex : 603,
										listeners : {
											check : {
												fn : this.onPetSelect,
												scope : this
											}
										},
										height : 19
									}]
						}]
					}, {
						xtype : 'container',
						itemId : 'cntOwnerChildrenAge',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form'
						},
						items : [{
									columnWidth : 0.33,
									items : [{
												xtype : 's-combobox',
												name : 'daysCount',
												fieldLabel : this.translations.days,
												mode : 'local',
												store : this.daysStore,
												displayField : 'days',
												allowBlank : false,
												width : 78,
												tabIndex : 607
											}]
								}, {
									xtype : 'container',
									itemId : 'cntChildrenAge',
									columnWidth : 0.66,
									defaults : {
										xtype : 'container',
										layout : 'form'
									},
									items : [{
												itemId : 'cntChildrenAgeLabel',
												defaults : {
													xtype : 'label'
												}
											}, {
												itemId : 'cntChildrenAgeBoxes',
												defaults : {
													xtype : 'container',
													layout : 'form',
													defaults : {
														allowBlank : false
													},
													style : {
														'padding-right' : '5px',
														'float' : 'left'
													}
												}
											}]
								}]
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 'container',
						itemId : 'cntRegion',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form'
						},
						items : [{
									columnWidth : .33,
									items : [{
												xtype : 'hlabel',
												text : this.translations.region
											}]
								}, {
									itemId : 'cntRegionGroup',
									columnWidth : 0.66,
									listeners : {
										afterrender : {
											fn : function() {
												this.regionsStore.load();
											},
											scope : this
										}
									}
								}]
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-fieldset',
						itemId : 'fsOfferVillas',
						checkboxName : 'offerForVillas',
						tabIndex : 1000,
						cls : 'bolded',
						title : this.translations.offerForVillas,
						collapsed : !showVillas,
						collapsible : true,
						checkboxToggle : true,
						autoHeight : true,
						items : [{
							xtype : 'container',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form',
								columnWidth : 0.33
							},
							items : [{
								items : [{
											xtype : 's-combobox',
											name : 'bedroomsCount',
											fieldLabel : this.translations.bedrooms,
											mode : 'local',
											store : this.bedroomsStore,
											displayField : 'bedrooms',
											name : 'bedroomsCount',
											editable : false,
											allowBlank : false,
											tabIndex : 1000
										}]
							}, {
								items : [{
											xtype : 's-combobox',
											name : 'bathroomsCount',
											fieldLabel : this.translations.bathrooms,
											mode : 'local',
											store : this.bathroomsStore,
											displayField : 'bathrooms',
											name : 'bathroomsCount',
											editable : false,
											allowBlank : false,
											tabIndex : 1000
										}]
							}]
						}, {
							xtype : 'checkbox',
							hideLabel : true,
							boxLabel : this.translations.pool,
							name : 'withPool',
							inputValue : 'yes',
							tabIndex : 1000
						}, {
							xtype : 'container',
							itemId : 'cntDistanceToSea',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form'
							},
							items : [{
								columnWidth : .33,
								items : [{
											xtype : 'label',
											text : this.translations.distanceToSea
										}]
							}, {
								columnWidth : .66,
								items : [{
									xtype : 'checkboxgroup',
									hideLabel : true,
									allowBlank : false,
									id : 'villasDistanceToSeaGroup',
									columns : 2,
									tabIndex : 701,
									defaults : {
										actAsRadio : false,
										groupID : 'villasDistanceToSeaGroup',
										listeners : {
											check : {
												fn : this.onCheckOption,
												scope : this
											}
										}
									},
									items : [{
										// xtype : 'radio',
										name : 'villaDistanceToSea',
										boxLabel : this.translations.anyDistance,
										checked : true,
										inputValue : this.translations.anyDistance,
										valueID : 'any',
										actAsRadio : true
									}, {
										boxLabel : this.translations.to150,
										name : 'villaDistanceToSea',
										inputValue : this.translations.to150,
										valueID : '0|150'
									}, {
										boxLabel : this.translations.to400,
										name : 'villaDistanceToSea',
										inputValue : this.translations.to400,
										valueID : '0|400'
									}, {
										boxLabel : this.translations.over400,
										name : 'villaDistanceToSea',
										inputValue : this.translations.over400,
										valueID : '401|99999'
									}]
								}]
							}]
						}, {
							xtype : 's-combobox',
							itemId : 'fldVillaCosts',
							fieldLabel : this.translations.maxVillaCosts,
							mode : 'remote',
							store : this.maxPriceVillaStore,
							displayField : this.maxPriceVillaField,
							name : this.maxPriceVillaField,
							valueField : this.maxPriceVillaField + 'ID',
							hiddenName : this.maxPriceVillaField + 'ID',
							tpl : '<tpl for="."><div class="x-combo-list-item">{'
									+ this.maxPriceVillaField
									+ '}<tpl if="xindex === 1">&nbsp;</tpl></div></tpl>',
							allowBlank : false,
							disabled : true,
							emptyText : this.translations.selectDates,
							queryParam : 'arrivalDate',
							tabIndex : 1000,
							listeners : {
								beforequery : {
									fn : function(queryEvent) {
										var fld = this
												.getComponent('cntParticipants')
												.getComponent('cntTravelDates')
												.getComponent('fldArrivalDate');
										var date = Ext.util.Format.date(fld
														.getValue(), 'Y-m-d');
										queryEvent.cancel = (queryEvent.query == date);
										queryEvent.query = date;
									},
									scope : this
								}
							}
						}, {
							xtype : 's-textarea',
							name : 'importantForVilla',
							fieldLabel : this.translations.importantForVilla,
							tabIndex : 1000,
							width : 589,
							height : 30
						}, {
							xtype : 's-additional-wishlist-objects',
							url : this.url,
							translations : this.translations,
							objectType : 'villa',
							objectList : this.villasList,
							checkObjects : this.villasList.length <= 1
						}],
						listeners : {
							expand : function() {
								this.markOfferAsInvalid(false);
							},
							scope : this
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-fieldset',
						itemId : 'fsOfferHotels',
						cls : 'bolded',
						checkboxName : 'offerForHotels',
						title : this.translations.offerForHotels,
						collapsed : !showHotels,
						collapsible : true,
						checkboxToggle : true,
						autoHeight : true,
						tabIndex : 2000,
						items : [{
							xtype : 's-hotel-offer',
							itemId : 'hotel-offer',
							translations : this.translations,
							url : this.url,
							hotelsList : this.hotelsList,
							requestFromWishlist : this.funnels
									&& this.funnels.gf === 'wishlist'
						}, {
							xtype : 's-additional-wishlist-objects',
							url : this.url,
							translations : this.translations,
							objectType : 'hotel',
							objectList : this.hotelsList,
							checkObjects : this.hotelsList.length <= 1
						}/*
							 * { xtype : 'container', itemId :
							 * 'cntOwnerHotelRooms', layout : 'column', defaults : {
							 * xtype : 'container', layout : 'form', columnWidth :
							 * 0.33 }, items : [{ items : [{ xtype :
							 * 's-combobox', name : 'hotelStars', fieldLabel :
							 * this.translations.stars, mode : 'remote', store :
							 * this.hotelStarStore, displayField :
							 * this.hotelStarField, valueField :
							 * this.hotelStarField + 'ID', editable : false,
							 * tabIndex : 2000, allowBlank : false }] }, { items : [{
							 * id : 'cmb-hotel-size', xtype : 's-combobox',
							 * fieldLabel : this.translations.hotelSize, mode :
							 * 'remote', store : this.hotelSizeStore,
							 * displayField : this.hotelSizeField, name :
							 * this.hotelSizeField, valueField :
							 * this.hotelSizeField + 'ID', hiddenName :
							 * this.hotelSizeField + 'ID', editable : false,
							 * tabIndex : 2000, allowBlank : false }] }, {
							 * itemId : 'cntHotelRooms' }] }, { xtype :
							 * 'radiogroup', columns : 4, fieldLabel :
							 * this.translations.forChildren, tabIndex : 2000,
							 * items : [{ boxLabel : this.translations.setBed,
							 * checked : true, name : 'forChildren', inputValue :
							 * 'setBed' }, { boxLabel :
							 * this.translations.seperateRoom, name :
							 * 'forChildren', inputValue : 'separateRoom' }] }, {
							 * itemId : 'cntBoardGroup', xtype : 'container',
							 * layout : 'form' }, { xtype : 'container', layout :
							 * 'form', hidden : !this.hasOneHotel, itemId :
							 * 'cntRoomCategory', items : [{ itemId :
							 * 'fldRoomCategory', xtype : 's-combobox',
							 * fieldLabel : this.translations.roomCategory, mode :
							 * 'remote', store : this.roomCategoryStore,
							 * displayField : this.roomCategoryField, name :
							 * this.roomCategoryField, valueField :
							 * this.roomCategoryField + 'ID', hiddenName :
							 * this.roomCategoryField + 'ID', allowBlank :
							 * false, editable : false, tabIndex : 100,
							 * queryParam : 'params', value : '', emptyText :
							 * this.translations.roomCategoryEmpty, disabled :
							 * true, width : 327, tpl : new Ext.XTemplate( '<tpl
							 * for="."><div class="x-combo-list-item">{' +
							 * this.roomCategoryField + '} (' +
							 * this.translations.priceFrom + '
							 * {[this.showPrice(values.roomPrice)]} ' +
							 * this.translations.euroPersonDay + ')</div></tpl>', {
							 * showPrice : function(price) { return
							 * Ext.util.Format.number( price, '0,00/i'); } }),
							 * listeners : { beforequery : { fn :
							 * function(queryEvent) { var arrivalFld = this
							 * .getArrivalDateFld(); var departureFld = this
							 * .getDepartureDateFld(); var boardArr = []
							 * this.getBoardGroupFld().items.each(
							 * function(item) { boardArr.push(item .getValue() ?
							 * 1 : 0); });
							 * 
							 * var args = { arrivalDate : arrivalFld
							 * .getRawValue(), departureDate : departureFld
							 * .getRawValue(), board : boardArr, hotelID :
							 * this.hasOneHotel ? this.expandItems.hotelID : 0 };
							 * var val = Ext.encode(args); queryEvent.cancel =
							 * (queryEvent.query == val); queryEvent.query =
							 * val; }, scope : this } } }] }, { xtype :
							 * 'container', itemId : 'cntHotelsDistanceToSea',
							 * layout : 'column', defaults : { xtype :
							 * 'container', layout : 'form' }, items : [{
							 * columnWidth : .33, items : [{ xtype : 'label',
							 * text : this.translations.distanceToSea }] }, {
							 * columnWidth : .66, items : [{ xtype :
							 * 'checkboxgroup', hideLabel : true, allowBlank :
							 * false, id : 'hotelsDistanceToSeaGroup', columns :
							 * 3, tabIndex : 701, defaults : { actAsRadio :
							 * false, groupID : 'hotelsDistanceToSeaGroup',
							 * listeners : { check : { fn : this.onCheckOption,
							 * scope : this } } }, items : [{ // xtype :
							 * 'radio', name : 'hotelDistanceToSea', boxLabel :
							 * this.translations.anyDistance, checked : true,
							 * inputValue : this.translations.anyDistance,
							 * valueID : '5', actAsRadio : true }, { boxLabel :
							 * String.format('{0} 200m',
							 * this.translations.upTo), name :
							 * 'hotelDistanceToSea', inputValue :
							 * String.format('{0} 200m',
							 * this.translations.upTo), valueID : '1' }, {
							 * boxLabel : String.format('{0} 400m',
							 * this.translations.upTo), name :
							 * 'hotelDistanceToSea', inputValue :
							 * String.format('{0} 400m',
							 * this.translations.upTo), valueID : '2' }, {
							 * boxLabel : String.format('{0} 800m',
							 * this.translations.upTo), name :
							 * 'hotelDistanceToSea', inputValue :
							 * String.format('{0} 800m',
							 * this.translations.upTo), valueID : '3' }, {
							 * boxLabel : String.format('{0} 800m',
							 * this.translations.moreThan), name :
							 * 'hotelDistanceToSea', inputValue :
							 * String.format('{0} 800m',
							 * this.translations.moreThan), valueID : '4' }] }] }] }, {
							 * xtype : 's-combobox', fieldLabel :
							 * this.translations.maxHotelCosts, mode : 'remote',
							 * store : this.maxPriceHotelStore, displayField :
							 * this.maxPriceHotelField, name :
							 * this.maxPriceHotelField, valueField :
							 * this.maxPriceHotelField + 'ID', hiddenName :
							 * this.maxPriceHotelField + 'ID', tabIndex : 2000,
							 * allowBlank : false }, { xtype : 's-textarea',
							 * name : 'importantForHotel', fieldLabel :
							 * this.translations.importantForHotel, tabIndex :
							 * 2000, width : 589, height : 30 }
							 */],
						listeners : {
							expand : function() {
								this.markOfferAsInvalid(false);
							},
							scope : this
						}
					}, {
						xtype : 's-spacer',
						style : this.defaultLanguage == 'Deutsch' ? '' : 'display: none'
					}, {
						xtype : 's-fieldset',
						itemId : 'fsOfferPlanes',
						checkboxName : 'offerForPlanes',
						title : this.translations.offerForPlane,
						collapsed : !showPlanes,
						collapsible : true,
						checkboxToggle : true,
						autoHeight : true,
						style : this.defaultLanguage == 'Deutsch' ? '' : 'display: none',
						tabIndex : 3000,
						items : [{
							xtype : 'container',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form',
								columnWidth : .33
							},
							items : [{
								items : [{
									xtype : 's-combobox',
									fieldLabel : this.translations.planeFrom,
									mode : 'remote',
									store : this.airportStore,
									displayField : this.airportField,
									name : this.airportField,
									valueField : this.airportField + 'ID',
									hiddenName : this.airportField + 'ID',
									tabIndex : 3000,
									allowBlank : false,
									tpl : new Ext.XTemplate(
											'<tpl for=".">{[this.showCountry(values.COUNTRYNAME)]}<div class="x-combo-list-item"><span class="airport-in-combobox">{'
													+ this.airportField
													+ '}</span></div></tpl>', {
												showCountry : function(
														countryname) {
													if (this.previous !== countryname) {
														this.previous = countryname;
														return String
																.format(
																		'<div class="country-in-combobox">{0}</div>',
																		countryname);
													}
													return '';
												}
											})
								}]
							}, {
								items : [{
									xtype : 's-combobox',
									fieldLabel : this.translations.planeTo,
									mode : 'remote',
									store : this.airportSardegnaStore,
									displayField : this.airportSardegnaField,
									name : this.airportSardegnaField,
									valueField : this.airportSardegnaField
											+ 'ID',
									hiddenName : this.airportSardegnaField
											+ 'ID',
									allowBlank : false,
									tabIndex : 3000,
									value : 'Cagliari'
								}]
							}, {}]
						}, {
							xtype : 's-travelers-group',
							translations : this.translations,
							travelersGroup : 'plane',
							relatedGroup : 'ferry',
							id : 'planeTravelersComponent'
						}],
						listeners : {
							collapse : function(fldset) {
								Ext.each(
										fldset.findByType('s-travelers-group'),
										function(item) {
											item.setCollapsed();
										});
							},
							expand : function(fldset) {
								this.markOfferAsInvalid(false);
								Ext.each(
										fldset.findByType('s-travelers-group'),
										function(item) {
											item.setExpanded();
										});
							},
							scope : this
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-fieldset',
						checkboxName : 'offerForCars',
						title : this.translations.offerForCar,
						collapsed : !showCars,
						collapsible : true,
						checkboxToggle : true,
						autoHeight : true,
						tabIndex : 4000,
						items : [{
							xtype : 'container',
							defaults : {
								xtype : 'container',
								layout : 'form'
							},
							items : [{
								items : [{
											xtype : 's-combobox',
											fieldLabel : this.translations.carClass,
											mode : 'remote',
											store : this.carclassStore,
											displayField : this.carclassField,
											name : this.carclassField,
											valueField : this.carclassField
													+ 'ID',
											hiddenName : this.carclassField
													+ 'ID',
											tabIndex : 4000,
											allowBlank : false
										}]
							}]
						}, {
							xtype : 'container',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form',
								columnWidth : .33
							},
							items : [{
								items : [{
									xtype : 's-combobox',
									fieldLabel : this.translations.pickup,
									mode : 'remote',
									store : this.rentalcarStationStore,
									displayField : this.rentalcarStationField,
									name : 'carPickup',
									valueField : this.rentalcarStationField
											+ 'ID',
									hiddenName : 'carPickupID',
									allowBlank : false,
									tabIndex : 4000,
									value : 'Cagliari Airport'
								}]
							}, {
								items : [{
									xtype : 's-combobox',
									fieldLabel : this.translations.dropoff,
									mode : 'remote',
									store : this.rentalcarStationStore,
									displayField : this.rentalcarStationField,
									name : 'carDropoff',
									valueField : this.rentalcarStationField
											+ 'ID',
									hiddenName : 'carDropoffID',
									allowBlank : false,
									tabIndex : 4000,
									value : 'Cagliari Airport'
								}]
							}]
						}, {
							xtype : 'container',
							defaults : {
								xtype : 'container',
								layout : 'form'
							},
							items : [{
								items : [{
											xtype : 's-integerfield',
											name : 'driverAge',
											fieldLabel : this.translations.driversAge,
											tabIndex : 4000,
											width : 78
										}]
							}]
						}, {
							xtype : 'radiogroup',
							columns : 4,
							fieldLabel : this.translations.driversLicense,
							tabIndex : 4000,
							items : [{
								boxLabel : this.translations.driversLicense3more,
								checked : true,
								name : 'driversLicense',
								inputValue : '1'
							}, {
								boxLabel : this.translations.driversLicense3less,
								name : 'driversLicense',
								inputValue : '0'
							}]
						}, {
							xtype : 'radiogroup',
							columns : 4,
							fieldLabel : '',
							tabIndex : 4000,
							items : [{
										boxLabel : this.translations.withDeductible,
										checked : true,
										name : 'deductible',
										inputValue : '1'
									}, {
										boxLabel : this.translations.withoutDeductible,
										name : 'deductible',
										inputValue : '0'
									}]
						}],
						listeners : {
							expand : function() {
								this.markOfferAsInvalid(false);
							},
							scope : this
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-fieldset',
						itemId : 'fsOfferFerries',
						checkboxName : 'offerForFerries',
						title : this.translations.offerForFerries,
						collapsed : !showFerries,
						collapsible : true,
						checkboxToggle : true,
						autoHeight : true,
						tabIndex : 5000,
						items : [{
							xtype : 'container',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form',
								columnWidth : .16
							},
							items : [{
								columnWidth : .33,
								items : [{
											xtype : 's-combobox',
											fieldLabel : this.translations.carType,
											mode : 'remote',
											store : this.cartypeStore,
											displayField : this.cartypeField,
											name : this.cartypeField,
											valueField : this.cartypeField
													+ 'ID',
											hiddenName : this.cartypeField
													+ 'ID',
											tabIndex : 5000,
											allowBlank : false
										}]
							}, {
								columnWidth : .17,
								items : [{
											xtype : 's-textfield',
											fieldLabel : this.translations.carMake,
											name : 'carmake',
											tabIndex : 5000,
											maxLength : 50,
											width : 56
										}]
							}, {
								items : [{
											xtype : 's-numericfield',
											fieldLabel : this.translations.carLength,
											name : 'carlength',
											allowBlank : false,
											tabIndex : 5000,
											width : 56
										}]
							}, {
								columnWidth : .17,
								items : [{
											xtype : 's-numericfield',
											fieldLabel : this.translations.carWidth,
											name : 'carwidth',
											allowBlank : false,
											tabIndex : 5000,
											width : 56
										}]
							}, {
								items : [{
											xtype : 's-numericfield',
											fieldLabel : this.translations.carHeight,
											name : 'carheight',
											tabIndex : 5000,
											width : 56
										}]
							}]
						}, {
							xtype : 'container',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form',
								columnWidth : .5
							},
							items : [{
								items : [{
									xtype : 's-combobox',
									fieldLabel : this.translations.ferryOutgoing,
									mode : 'remote',
									store : this.ferryRouteStore,
									displayField : this.ferryRouteField,
									name : this.ferryRouteField + 'Outgoing',
									valueField : this.ferryRouteField + 'ID',
									hiddenName : this.ferryRouteField
											+ 'OutgoingID',
									allowBlank : false,
									tabIndex : 5000,
									width : 250
								}]
							}, {
								items : [{
									xtype : 's-combobox',
									fieldLabel : this.translations.ferryReturn,
									mode : 'remote',
									store : this.ferryRouteStoreSardegna,
									displayField : this.ferryRouteFieldSardegna,
									name : this.ferryRouteField + 'Return',
									valueField : this.ferryRouteFieldSardegna
											+ 'ID',
									hiddenName : this.ferryRouteField
											+ 'ReturnID',
									allowBlank : false,
									tabIndex : 5000,
									width : 250
								}]
							}]
						}, {
							xtype : 'container',
							layout : 'column',
							defaults : {
								xtype : 'container',
								layout : 'form',
								columnWidth : .5
							},
							items : [{
								items : [{
											xtype : 's-combobox',
											fieldLabel : this.translations.cabinType,
											mode : 'remote',
											store : this.cabintypeStore,
											displayField : this.cabintypeField,
											name : this.cabintypeField,
											valueField : this.cabintypeField
													+ 'ID',
											hiddenName : this.cabintypeField
													+ 'ID',
											tabIndex : 5000,
											allowBlank : false
										}]
							}]
						}, {
							xtype : 's-travelers-group',
							translations : this.translations,
							travelersGroup : 'ferry',
							relatedGroup : 'plane',
							id : 'ferryTravelersComponent'
						}],
						listeners : {
							collapse : function(fldset) {
								Ext.each(
										fldset.findByType('s-travelers-group'),
										function(item) {
											item.setCollapsed();
										});
							},
							expand : function(fldset) {
								this.markOfferAsInvalid(false);
								Ext.each(
										fldset.findByType('s-travelers-group'),
										function(item) {
											item.setExpanded();
										});
							},
							scope : this
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form'
						},
						items : [{
							columnWidth : .33,
							items : [{
										xtype : 'label',
										text : this.translations.specialDesires,
										style : 'font-size: 11px'
									}]
						}, {
							columnWidth : .66,
							items : [{
										xtype : 's-textarea',
										name : 'specialDesires',
										hideLabel : true,
										tabIndex : 6000,
										width : 388,
										height : 45
									}]
						}]
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-combobox',
						fieldLabel : this.translations.howFound,
						mode : 'remote',
						store : this.howfoundStore,
						displayField : this.howfoundField,
						tabIndex : 7000,
						valueField : this.howfoundField + 'ID',
						hiddenName : this.howfoundField + 'ID'
					}],
			buttons : [{
						text : this.translations.requestOffer,
						handler : this.onRequestOffer,
						scope : this
					}],
			buttonAlign : 'right'
		});

		Ext.ux.RequestHolidayRental.superclass.createItems.apply(this,
				arguments);

		this.on({
					afterrender : this.onAfterRender,
					show : function() {
						var header = document
								.getElementById('requestHolidayRentalHeaderCmp');
						if (header)
							header.style.display = 'block';
					},
					hide : function() {
						var header = document
								.getElementById('requestHolidayRentalHeaderCmp');
						if (header)
							header.style.display = 'none';
					},
					regionsLoaded : this.onRegionsLoad,
					scope : this
				});
	},
	onRequestOffer : function() {
		if (this.getForm().isValid()) {
			if (this.validateTravelDates() && this.isOfferSelected()) {
				var values = this.getForm().getValues();

				var p = {};
				this.getForm().items.each(function(item) {
							if (item instanceof Ext.form.ComboBox && item.name
									&& item.name.length) {
								p[item.name] = item.getRawValue();
							} else if (item.getXType() === 'checkboxgroup'
									&& item.items
									&& item.items instanceof Ext.util.MixedCollection) {
								item.items.each(function(subitem) {
											if (subitem.checked) {
												var sufix = subitem.name
														.indexOf('board') === 0
														? '_Data'
														: 'Data';
												if (!p[subitem.name + sufix])
													p[subitem.name + sufix] = [];
												p[subitem.name + sufix]
														.push(subitem.valueID);
											}
										});
							} /*
								 * else if (values.offerForPlanes &&
								 * !values.offerForFerries ||
								 * !values.offerForPlanes &&
								 * values.offerForFerries) { if (item instanceof
								 * Ext.form.TextField && item.name &&
								 * item.name.indexOf('travelerFirstName') > 0)
								 * p[String.format('{0}_travelerSelected{1}',
								 * item.name.substring(0, item.name
								 * .indexOf('_')), item.name.substring(item.name
								 * .lastIndexOf('_')))] = 'on'; }
								 */
						});
				Ext.applyIf(values, p);

				p = {
					cmd : 'saveRequestOffer',
					isLoggedIn : GLOBAL.isLoggedIn,
					contactsToDelete : this.contactsToDelete || '',
					villaID : this.expandItems && this.expandItems.villaID
							? this.expandItems.villaID
							: '',
					hotelID : this.expandItems && this.expandItems.hotelID
							? this.expandItems.hotelID
							: ''
				};
				Ext.applyIf(p, values);

				this.valuesForStateSave = values;
				this.fireEvent('saveState');

				var review = Ext.getCmp('requestHolidayRentalReviewCmp');
				if (review) {
					review.setFormParams(p);
					review.showReview(values, this.translations);
					this.hide();
				}
			}
		} else {
			var fld = this.getForm().items.find(function(item) {
						var cnt = item.findParentByType('s-fieldset');
						if (!cnt || cnt && !cnt.collapsed) {
							return !item.isValid(true);
						}
						return false;
					});
			if (fld)
				fld.focus();
		}
	},
	onChildrenSelect : function(combo, record, index) {
		var count = record instanceof Ext.data.Record
				? record.get('children')
				: parseInt(record);

		var hotelOffer = this.getComponent('fsOfferHotels')
				.getComponent('hotel-offer');
		if (hotelOffer)
			hotelOffer.showChildrenBeds(this, count);

		var cnt = this.getComponent('cntOwnerChildrenAge')
				.getComponent('cntChildrenAge')
				.getComponent('cntChildrenAgeBoxes');

		if (cnt) {
			var cmpArray = cnt.findByType('container');
			Ext.each(cmpArray, function(form, idx, all) {
						var items = form.findByType('combo');
						Ext.each(items, function(field) {
									field.clearInvalid();
								});
					});
			var items = [];
			if (cmpArray.length <= count) {
				for (var i = cmpArray.length; i < count; i++)
					items.push({
								items : [{
									xtype : 's-combobox',
									fieldLabel : String.format('{0} {1}',
											this.translations.child, i + 1),
									mode : 'local',
									store : {
										xtype : 'arraystore',
										autoDestroy : true,
										fields : [{
													name : 'childage',
													type : 'int'
												}],
										data : this.generateArray(18, 1)
									},
									displayField : 'childage',
									name : 'childrenages',
									editable : false,
									width : 70,
									tabIndex : 608
								}]
							});
				cnt.add(items);
			} else {
				for (var i = count; i < cmpArray.length; i++)
					cnt.remove(cmpArray[i], true);
			}
			cnt.doLayout();
		}
		cnt = this.getComponent('cntOwnerChildrenAge')
				.getComponent('cntChildrenAge')
				.getComponent('cntChildrenAgeLabel');
		if (cnt) {
			var cmpArray = cnt.findByType('label');
			if (count && cmpArray.length === 0) {
				cnt.add({
							text : this.translations.childrenAge
						});
				cnt.doLayout();
			} else if (count === 0) {
				cnt.remove(cmpArray[0]);
				cnt.doLayout();
			}
		}
		Ext.each(this.findByType('s-travelers-group'), function(group) {
					group.setMaxChildrenTravelers(count);
				});
	},
	onAdultsSelect : function(combo, record, index) {
		var count = record instanceof Ext.data.Record
				? record.get('adults')
				: record;
		var cmp = this.getComponent('fsOfferHotels')
				.getComponent('hotel-offer');
		if (cmp)
			cmp.showRooms(count > 1);
		Ext.each(this.findByType('s-travelers-group'), function(group) {
					group.setMaxAdultsTravelers(count);
				});
	},
	onAddPhoneNumber : function(genHidden) {
		var cnt = this.getComponent('cntAdditionalPhone');
		if (!this.phoneCounter)
			this.phoneCounter = 2;
		if (cnt) {
			var groupCfg = this.generateContactTypeGroup(2,
					'cntAdditionalPhone', this.phoneCounter);

			var listItems = [{
				xtype : 's-textfield',
				hideLabel : true,
				maxLength : 10,
				name : 'phoneCountryCode_' + this.phoneCounter,
				width : 38,
				value : this
						.getCountryCode(Ext.getCmp('countryCmb').getValue()),
				tabIndex : 200
			}];
			if (genHidden === true)
				listItems.push({
							itemId : 'hiddenID',
							xtype : 'hidden',
							name : 'phoneID_' + this.phoneCounter
						});
			cnt.add({
				itemId : 'cntAdditionalPhone' + this.phoneCounter,
				// height : 30,
				defaults : {
					xtype : 'container',
					layout : 'form',
					labelAlign : 'top'
				},
				items : [{
							itemId : 'firstCmp',
							columnWidth : .075,
							items : listItems
						}, {
							columnWidth : .075,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 10,
										name : 'phonePrefix_'
												+ this.phoneCounter,
										width : 38,
										tabIndex : 200
									}]
						}, {
							columnWidth : 0.15,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 28,
										name : 'phone_' + this.phoneCounter,
										width : 83,
										tabIndex : 200
									}]
						}, {
							columnWidth : 0.6,
							itemId : 'cntAdditionalPhone',
							items : groupCfg
						}, {
							style : {
								paddingTop : '6px'
							},
							columnWidth : 0.1,
							items : [{
								xtype : 'llabel',
								text : this.translations.remove,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
												click : {
													fn : function(ev, html,
															options) {
														var owner = cmp.ownerCt.ownerCt.ownerCt;
														var hidden = cmp.ownerCt.ownerCt
																.getComponent('firstCmp')
																.getComponent('hiddenID');
														// console.log(hidden
														// .getValue());
														if (hidden) {
															var root = owner.ownerCt;
															if (!root.contactsToDelete)
																root.contactsToDelete = hidden
																		.getValue();
															else
																root.contactsToDelete = root.contactsToDelete
																		+ ','
																		+ hidden
																				.getValue();
														}

														owner
																.remove(
																		cmp.ownerCt.ownerCt,
																		true);
														owner.doLayout();
													},
													scope : cmp
												}
											});
										},
										scope : this
									}
								}
							}]
						}]
			});
			cnt.doLayout();
			this.getForm().setValues(this.loadedData);
			this.phoneCounter++;
		}
	},
	showFaxButton : function(show) {
		var faxButton = this.getComponent('cntAdditionalFaxPhoneButtons')
				.getComponent('cntAdditionalFaxButton');
		if (faxButton) {
			if (show)
				faxButton.show();
			else
				faxButton.hide();
		}
	},
	onAddFaxNumber : function(genHidden) {
		var cnt = this.getComponent('cntAdditionalFax');
		var counter = 1;
		if (cnt && cnt.findByType('container').length === 0) {
			this.showFaxButton(false);
			cnt.add({
						layout : 'form',
						items : [{
									xtype : 'label',
									text : this.translations.fax,
									style : 'font-size: 11px'
								}]
					});
			var groupCfg = this.generateContactTypeGroup(3, 'cntAdditionalFax',
					counter);
			var listItems = [{
				xtype : 's-textfield',
				hideLabel : true,
				maxLength : 10,
				name : 'faxCountryCode_1',
				value : this
						.getCountryCode(Ext.getCmp('countryCmb').getValue()),
				tabIndex : 300,
				width : 38
			}];
			if (genHidden === true)
				listItems.push({
							itemId : 'hiddenID',
							xtype : 'hidden',
							name : 'faxID_' + counter
						});
			cnt.add({
				itemId : 'cntAdditionalFax' + counter,
				// height : 40,
				defaults : {
					xtype : 'container',
					layout : 'form',
					labelAlign : 'top'
				},
				items : [{
							itemId : 'firstCmp',
							columnWidth : 0.075,
							items : listItems
						}, {
							columnWidth : 0.075,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 10,
										name : 'faxPrefix_1',
										tabIndex : 300,
										width : 38
									}]
						}, {
							columnWidth : 0.15,
							items : [{
										xtype : 's-textfield',
										hideLabel : true,
										maxLength : 28,
										name : 'fax_1',
										tabIndex : 300,
										width : 83
									}]
						}, {
							itemId : 'cntAdditionalFax',
							columnWidth : 0.6,
							items : groupCfg
						}, {
							columnWidth : 0.1,
							items : [{
								xtype : 'llabel',
								text : this.translations.remove,
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
												click : {
													fn : function(ev, html,
															options) {
														var owner = cmp.ownerCt.ownerCt.ownerCt;
														var hidden = cmp.ownerCt.ownerCt
																.getComponent('firstCmp')
																.getComponent('hiddenID');
														// console.log(hidden
														// .getValue());
														if (hidden) {
															var root = owner.ownerCt;
															if (!root.contactsToDelete)
																root.contactsToDelete = hidden
																		.getValue();
															else
																root.contactsToDelete = root.contactsToDelete
																		+ ','
																		+ hidden
																				.getValue();
														}
														/*
														 * owner .remove(
														 * cmp.ownerCt.ownerCt,
														 * true);
														 */
														owner.removeAll(true);
														owner.doLayout();
													},
													scope : cmp
												}
											});
										},
										scope : this
									}
								}
							}]
						}],
				listeners : {
					destroy : function() {
						this.showFaxButton(true);
					},
					scope : this
				}
			});
			cnt.doLayout();
			this.getForm().setValues(this.loadedData);
		}
	},
	onAddEmail : function(genHidden) {
		var cnt = this.getComponent('cntAdditionalEmail');
		if (!this.emailCounter)
			this.emailCounter = 1;
		if (cnt) {
			if (cnt.findByType('container').length === 0)
				cnt.add({
							layout : 'form',
							items : [{
										xtype : 'label',
										text : this.translations.additionalEmail,
										style : 'font-size: 11px'
									}]
						});

			var groupCfg = this.generateContactTypeGroup(1,
					'cntAdditionalEmail', this.emailCounter);
			var listItems = [{
						xtype : 's-textfield',
						hideLabel : true,
						maxLength : 100,
						name : 'additionalEmail_' + this.emailCounter,
						width : 225,
						tabIndex : 1,
						vtype : 'email'
					}];
			if (genHidden === true)
				listItems.push({
							itemId : 'hiddenID',
							xtype : 'hidden',
							name : 'additionalEmailID_' + this.emailCounter
						});
			cnt.add({
				itemId : 'cntAdditionalEmail' + this.emailCounter,
				// height : cnt.findByType('container').length ? 30 : 43,
				defaults : {
					xtype : 'container',
					layout : 'form',
					labelAlign : 'top'
				},
				items : [{
							itemId : 'firstCmp',
							columnWidth : 0.4,
							items : listItems
						}, {
							itemId : 'cntAdditionalEmail',
							columnWidth : 0.5,
							items : groupCfg
						}, {
							columnWidth : 0.1,
							items : [{
								xtype : 'llabel',
								text : this.translations.remove,
								ctCls : cnt.findByType('container').length
										? ''
										: 'label-top-spacer',
								listeners : {
									afterrender : {
										fn : function(cmp) {
											cmp.getEl().on({
												click : {
													fn : function(ev, html,
															options) {
														var owner = cmp.ownerCt.ownerCt.ownerCt;
														var hidden = cmp.ownerCt.ownerCt
																.getComponent('firstCmp')
																.getComponent('hiddenID');
														// console.log(hidden
														// .getValue());
														if (hidden) {
															var root = owner.ownerCt;
															if (!root.contactsToDelete)
																root.contactsToDelete = ''
																		+ hidden
																				.getValue();
															else
																root.contactsToDelete = root.contactsToDelete
																		+ ','
																		+ hidden
																				.getValue();
														}
														owner
																.remove(
																		cmp.ownerCt.ownerCt,
																		true);
														if (owner
																.findByType('container').length === 1)
															owner
																	.removeAll(true);
														owner.doLayout();
													},
													scope : cmp
												}
											});
										},
										scope : this
									}
								}
							}]
						}]
			});
			cnt.doLayout();
			this.getForm().setValues(this.loadedData);
			this.emailCounter++;
		}
	},
	onCheckOption : function(fld, value) {
		if (value) {
			Ext.getCmp(fld.groupID).items.each(function(item) {
						if (item.actAsRadio == !fld.actAsRadio) {
							item.setValue(false);
						}
					});
		}
	},
	onBlurEmail : function(field) {
		if (field.isValid()) {
			Ext.Ajax.request({
						url : this.url,
						success : this.onCheckUser,
						scope : this,
						params : {
							cmd : 'checkUser',
							username : field.getValue()
						}
					});
			var cnt = this.getComponent('cntOwnerEmailCheck')
					.getComponent('cntEmailCheck');
			if (cnt) {
				cnt.add({
							xtype : 'box',
							autoEl : {
								tag : 'div',
								cls : 'loading-indicator',
								html : this.translations.checkingEmail
							}
						});
				cnt.doLayout();
			}
		}
	},
	onPetSelect : function(checkbox, newVal, oldVal) {
		// console.log(newVal);
		var cnt = this.getComponent('cntParticipants')
				.getComponent('cntPetDescription');
		// console.log(cnt);
		if (cnt) {
			if (newVal) {
				cnt.add({
							xtype : 's-textfield',
							itemId : 'fldPetDescription',
							name : 'petDescription',
							fieldLabel : this.translations.petDesc,
							width : 194,
							tabIndex : 606
						});
				cnt.doLayout();
			} else {
				var r = cnt.getComponent('fldPetDescription');
				if (r) {
					cnt.remove(r, true);
					cnt.doLayout();
				}
			}
		}
	},
	onCheckUser : function(response, options) {
		var cnt = this.getComponent('cntOwnerEmailCheck')
				.getComponent('cntEmailCheck');
		if (cnt) {
			cnt.removeAll(true);
			cnt.doLayout();
		}
		var result = Ext.ux.RequestHolidayRental.superclass.onSuccess.apply(
				this, arguments);
		if (result.isKnown && !result.isLoggedIn) {
			var loginForm = Ext.getCmp('requestHolidayRentalLoginCmp');
			if (loginForm) {
				loginForm.setUsername(result.username);
				loginForm.show();
				this.hide();
			}
		}
	},
	loadUserData : function() {
		this.getForm().load({
					url : this.url,
					params : {
						cmd : 'getUserData'
					},
					success : function(form, action) {
						var data = action.result.data;
						this.loadedData = data;
						if (data.phoneCounter - 1 > 0) {
							for (var i = 0; i < data.phoneCounter - 1; i++)
								this.onAddPhoneNumber(true);
						}
						if (data.faxCounter > 0) {
							for (var i = 0; i < data.faxCounter; i++)
								this.onAddFaxNumber(true);
							this.itemsToLoad++;
						}
						if (data.emailCounter > 0) {
							for (var i = 0; i < data.emailCounter; i++)
								this.onAddEmail(true);
							this.itemsToLoad++;
						}
						// this.getForm().setValues(this.savedValues);
						form.setValues(data);

						this.loadDataFromCookie();

						this.itemLoaded();
					},
					failure : function() {
						this.loadDataFromCookie();
						this.itemLoaded();
					},
					scope : this
				});
	},
	loadDataFromCookie : function() {
		if (this.savedState) {
			this.getForm().setValues(this.savedState);
			if (this.savedState.adultsCount)
				this.onAdultsSelect(null, this.savedState.adultsCount);
			if (this.savedState.childrenCount) {
				this.onChildrenSelect(null, this.savedState.childrenCount);
				this.fillChildrenAges(this.savedState.childrenages)
			}
			if (this.regionsLoaded)
				this.fillSelectedRegions(this.savedState.regionsData);
			else
				this.regionsToSelect = this.savedState.regionsData;
			if (this.savedState.arrivalDate && this.savedState.departureDate) {
				this.enableVillaPrices();
				this.updateHotelsData();
			}
		}
	},
	generateContactTypeGroup : function(contactType, container, index) {
		var result = [];
		var generateName = function(tt, ii) {
			var type = 'phone';
			switch (tt) {
				case 1 :
					type = 'additionalEmail';
					break;
				case 2 :
					type = 'phone';
					break;
				case 3 :
					type = 'fax';
			}
			return String.format('{0}Type_{1}', type, ii);
		};
		var generateGroupName = function(tt, ii) {
			var type = 'phone';
			switch (tt) {
				case 1 :
					type = 'additionalEmail';
					break;
				case 2 :
					type = 'phone';
					break;
				case 3 :
					type = 'fax';
			}
			return String.format('group{0}{1}', type, ii);
		};
		var generateTabIndex = function(tt) {
			var tb = 1;
			switch (tt) {
				case 1 :
					tb = 1;
					break;
				case 2 :
					tb = 200;
					break;
				case 3 :
					tb = 300;
			}
			return tb;
		};

		if (!this.contactGroups)
			this.contactGroups = {};
		if (this.contactGroups['group' + contactType]) {
			var o = this.contactGroups['group' + contactType];
			for (var i = 0, len = o.items.length; i < len; i++)
				Ext.apply(o.items[i], {
							name : generateName(contactType, index),
							tabIndex : generateTabIndex(contactType)
						});
			result = [o];
		} else {
			new Ext.data.JsonStore({
				url : this.url,
				cnt : container,
				idx : index,
				baseParams : {
					cmd : 'getContactTypes',
					type : contactType
				},
				fields : [{
							name : 'boxLabel'
						}, {
							name : 'inputValue'
						}],
				root : 'data',
				idProperty : 'inputValue',
				autoLoad : true,
				listeners : {
					'load' : {
						fn : function(store, records, options) {
							this.itemLoaded();
							var checkboxItems = [];
							var counter = 0;
							Ext.each(records, function(record, idx, all) {
										checkboxItems[counter] = record.data;
										Ext.apply(checkboxItems[counter], {
													name : generateName(
															store.baseParams.type,
															store.idx),
													// id : 'phoneType-option-'
													// + record.data.inputValue,
													checked : counter === 0,
													inputValue : ''
															+ record.data.inputValue
												});
										counter++;
									});
							this.contactGroups['group' + store.baseParams.type] = {
								xtype : 'radiogroup',
								name : generateGroupName(store.baseParams.type,
										store.idx),
								hideLabel : true,
								items : checkboxItems,
								columns : 3,
								tabIndex : generateTabIndex(contactType)
								// store.baseParams.type === 1 ? 3 : 4
							};

							var cnt = this.getComponent(store.cnt)
									.getComponent(store.cnt + store.idx)
									.getComponent(store.cnt);

							if (Ext.isIE6) {
								var o = this.contactGroups['group'
										+ store.baseParams.type];
								Ext.apply(o, {
											width : cnt.getWidth()
										});
								cnt.add(o);
							} else {
								cnt.add(this.contactGroups['group'
										+ store.baseParams.type]);
							}

							cnt.doLayout();
							this.getForm().setValues(this.loadedData);
						},
						scope : this
					}
				}
			});
		}
		return result;
	},
	onAfterRender : function() {
		if (this.loadingIndicatorId && Ext.get(this.loadingIndicatorId))
			Ext.get(this.loadingIndicatorId).remove();
		var mask = this.getEl().mask(this.translations.pleaseWait);
		if (Ext.isIE6) {
			this.maskEl = mask;
			this.task = {
				run : function() {
					this.maskEl.setHeight(this.getEl().getHeight());
				},
				interval : 250,
				scope : this
			};
			Ext.TaskMgr.start(this.task);
		}

		this.loadUserData();
	},
	unmask : function() {
		if (Ext.isIE6 && this.task) {
			Ext.TaskMgr.stop(this.task);
		}
		if (this.rendered && this.itemsToLoad <= 0)
			this.getEl().unmask();
	},
	itemLoaded : function() {
		this.itemsToLoad--;
		this.unmask();
	},
	onCountrySelect : function(combo, newVal, oldVal) {
		var fields = this.findFields('phoneCountryCode_', 'faxCountryCode_1');
		var countryCode = this.getCountryCode(newVal);
		Ext.each(fields, function(fld) {
					fld.setValue(countryCode);
				});
	},
	getCountryCode : function(countryID) {
		var s = this.countryStore;
		var idx = s.find(this.countryField + 'ID', countryID);
		if (idx >= 0) {
			var rec = s.getAt(idx);
			if (rec)
				return rec.get('COUNTRYPHONECODE');
		}
		return '';
	},
	findFields : function(nameStartsWith, nameStartsWith2) {
		var fun = function(cmp, cnt) {
			return cmp.name && cmp.name.length ? cmp.name
					.indexOf(nameStartsWith) === 0
					|| cmp.name.indexOf(nameStartsWith2) === 0 : false;
		}
		return this.findBy(fun);
	},
	updateHotelsData : function() {
		var arrivalFld = this.getArrivalDateFld();
		var departureFld = this.getDepartureDateFld();
		if (arrivalFld && departureFld && arrivalFld.isValid()
				&& departureFld.isValid()) {
			var cmp = this.getComponent('fsOfferHotels')
					.getComponent('hotel-offer');
			if (cmp)
				cmp.updateTravelDates(arrivalFld.getRawValue(), departureFld
								.getRawValue());
		}
	},
	getArrivalDateFld : function() {
		return this.getComponent('cntParticipants')
				.getComponent('cntTravelDates').getComponent('fldArrivalDate');
	},
	getDepartureDateFld : function() {
		return this.getComponent('cntParticipants')
				.getComponent('cntTravelDates')
				.getComponent('fldDepartureDate');
	},
	isOfferSelected : function() {
		var result = false;
		Ext.each(this.findByType('fieldset'), function(fldset) {
					if (!fldset.collapsed) {
						result = true;
					}
				});

		this.markOfferAsInvalid(!result);

		return result;
	},
	markOfferAsInvalid : function(invalid) {
		var isInvalid = false || invalid;
		var errMsg = this.footer.child('div.x-form-invalid-msg');
		if (isInvalid) {
			if (!errMsg)
				this.footer
						.insertHtml(
								'afterBegin',
								String
										.format(
												'<div class="x-form-invalid-msg" style="width: 100%;">{0}</div>',
												this.translations.selectOffer));
			Ext.each(this.findByType('fieldset'), function(fldset) {
						if (fldset.checkbox && !fldset.checkbox.up('span', 1))
							fldset.checkbox.wrap({
										tag : 'span',
										cls : 'SardegnaForm-invalid-checkbox'
									});
					}, this);
		} else {
			if (errMsg)
				errMsg.remove();
			Ext.each(this.findByType('fieldset'), function(fldset) {
						fldset.checkbox.unwrap('span');
					}, this);
		}
	},
	fillChildrenAges : function(ages) {
		ages = String.format('{0}', ages).split(',');
		if (ages.length && ages[0] != '') {
			var ii = 0;
			var cnt = this.getComponent('cntOwnerChildrenAge')
					.getComponent('cntChildrenAge')
					.getComponent('cntChildrenAgeBoxes');
			Ext.each(cnt.findByType('combo'), function(combo) {
						if (ii < ages.length) {
							combo.setValue(ages[ii]);
							ii++;
						} else
							return false;
					});
		}
	},
	onRegionsLoad : function() {
		this.regionsLoaded = true;
		if (this.regionsToSelect)
			this.fillSelectedRegions(this.regionsToSelect);
	},
	fillSelectedRegions : function(regionsToSelect) {
		if (regionsToSelect && this.getForm())
			this.getForm().setValues(regionsToSelect);
	},
	enableVillaPrices : function() {
		var arrivalFld = this.getComponent('cntParticipants')
				.getComponent('cntTravelDates').getComponent('fldArrivalDate');
		var valid = true;
		if (arrivalFld)
			valid = arrivalFld.isValid(true);

		var cb = this.getComponent('fsOfferVillas')
				.getComponent('fldVillaCosts');
		if (cb) {
			if (valid) {
				cb.enable();
				cb.emptyText = '';
			} else {
				cb.disable();
				cb.emptyText = this.translations.selectDates;
			}
			cb.reset();
		}
	},
	validateTravelDates : function() {
		var result = true;

		var arr = this.getArrivalDateFld();
		var dep = this.getDepartureDateFld();

		var arrDate = arr.parseDate(arr.getValue());
		var depDate = dep.parseDate(dep.getValue());

		if ((depDate.getTime() - arrDate.getTime()) < 0) {
			result = false;
			dep.markInvalid(String.format(this.translations.minDateText
							+ ' {0}', arr.getRawValue()));
			dep.focus();
		}
		return result;
	}
});
Ext.ns('Ext.ux');

Ext.ux.RequestHolidayRentalReview = Ext.extend(Ext.ux.SardegnaForm, {
	layout : 'fit',
	hidden : true,
	translations : {
		requestOffer : 'Request offer',
		changeRequest : 'Change Request',
		thankYouText : 'request review thankyou text',
		reviewText : 'request review header',
		daysUnit : 'days',
		daysUnit1 : 'day',
		participants : 'Participants',
		offerForVillasForYou : 'You want an offer for villas',
		minimum : 'min.',
		bedroomUnit : 'Bedrooms',
		bedroomUnit1 : 'Bedroom',
		bathroomUnit : 'Bathrooms',
		bathroomUnit1 : 'Bathroom',
		maxCostPerPersonVilla : 'Maximum price of the house',
		maxCostPerPersonHotel : 'Maximum price of the hotel',
		currencyUnit : 'euro',
		offerForHotelsForYou : 'You want an offer for hotels',
		travelTime : 'Travel dates',
		roomsUnit : 'Rooms unit',
		roomsUnit1 : 'Room',
		offerForPlaneForYou : 'You want an offer for planes',
		offerForCarForYou : 'You want an offer for rental cars',
		offerForFerriesForYou : 'You want an offer for ferries',
		footer : 'request review footer',
		withPet : 'with pet',
		withoutPet : 'without pet',
		stayLength : 'Length of stay',
		withPool : 'with pool',
		withoutPool : 'without pool',
		flexibleDates : 'flexible',
		fixedDates : 'fixed',
		yourSpecialDesires : 'Your special desires',
		adultsUnit : 'adults [lower case]',
		childrenUnit : 'child [lower case]',
		adultsUnit1 : 'adult',
		childrenUnit1 : 'child unit',
		sendingOffer : 'Sending request...',
		hotelsOffer : 'Hotels',
		villasOffer : 'Villas',
		years : 'years',
		forChildrenlc : 'For children 2',
		setBedlc : 'additional bed 2',
		seperateRoomlc : 'separate room 2',
		withDeductible2 : 'With deductible 2',
		withoutDeductible2 : 'Without deductible 2',
		newsletter : 'I would like to receive newsletter',
		answerYes : 'Yes',
		answerNo : 'No'
	},
	createItems : function() {

		this.actions = {
			submit : new Ext.Action({
						text : this.translations.requestOffer,
						handler : this.onRequestOffer,
						scope : this,
						width : 200
					}),
			back : new Ext.Action({
						text : this.translations.changeRequest,
						handler : this.onChangeRequest,
						scope : this,
						width : 200
					})
		};

		Ext.apply(this, {
					items : [{
								itemId : 'review-content',
								xtype : 'box'
							}],
					buttons : [this.actions.back, this.actions.submit],
					buttonAlign : 'center'

				});

		Ext.ux.RequestHolidayRentalReview.superclass.createItems.apply(this,
				arguments);
	},
	showReview : function(data, translations) {
		this.show();
		Ext.apply(data, {
					villas : [],
					hotels : []
				});
		this.data = data;
		if (!this.loaded) {
			Ext.apply(this.translations, translations);
			this.loaded = true;
		}
		var trn = this.translations;

		var wrapTitle = function(text, quotes) {
			return String.format(
					'<div class={1}request-review-header{1}>{0}</div>', text,
					quotes ? quotes : '"');
		}

		var wrapLabel = function(text) {
			return String.format(
					'<span class="request-review-label">{0}</span>', text);
		}

		var sep = ':';
		var wl = wrapLabel;
		var wt = wrapTitle;
		var wts = function(text) {
			return String.format(
					'<span class="request-review-header">{0}</span>', text);
		}

		var villasTmpl = '';
		var hr = '<div class="SardegnaForm-Spacer"></div>';
		var hrc = '<div class="SardegnaForm-Spacer clear"></div>';

		var villasListTmpl = '';
		if (this.data.offerForVillas === 'on') {
			villasTmpl = wrapTitle(this.translations.offerForVillasForYou)
					+ wl(this.translations.minimum)
					+ ' {bedroomsCount} '
					+ '{[this.showBedroomUnits(values.bedroomsCount)]}<br/>'
					+ wl(this.translations.minimum)
					+ ' {bathroomsCount} '
					+ '{[this.showBathroomUnits(values.bathroomsCount)]}<br/>'
					+ '{[this.showPool(values.withPool)]}<br/>'
					+ wl(this.translations.distanceToSea + sep)
					+ ' {[this.formatList(values.villaDistanceToSea)]}<br/>'
					+ wl(this.translations.maxCostPerPersonVilla + sep)
					+ ' {[this.showCosts(values.range)]}<br/>{[this.showImportantForVilla(values.importantForVilla)]}'
					+ hr;
			villasListTmpl = '<div class="request-review-left">'
					+ '<tpl for="villas">' + '{[xindex === 1 ? "'
					+ wt(this.translations.villasOffer + sep, "'") + '" : ""]}'
					+ '<div style="margin: 5px 0;"> - {.}</div>'
					+ '</tpl></div>';
		}

		var hotelsTmpl = '';
		var hotelsListTmpl = '';
		// console.log(data);
		if (this.data.offerForHotels === 'on') {
			hotelsTmpl = wrapTitle(this.translations.offerForHotelsForYou);
			if (this.formParams.hotelID.length) {
				hotelsTmpl += wl(this.translations.forChildrenlc + sep)
						+ ' {[this.showForChildren(values.forChildren)]}<br/>'
						+ '{[this.showHotelsData(values)]}' + hr;
			} else
				hotelsTmpl += wl(this.translations.stars + sep)
						+ ' {hotelStars}<br/>'
						+ wl(this.translations.hotelSize + sep)
						+ ' {HOTELSIZE}<br/>'
						+ '{[this.showRooms(values.hotelRooms)]}'
						+ wl(this.translations.forChildrenlc + sep)
						+ ' {[this.showForChildren(values.forChildren)]}<br/>'
						+ wl(this.translations.board + sep)
						+ ' {[this.formatList(values["board_0"])]}<br/>'
						+ wl(this.translations.distanceToSea + sep)
						+ ' {[this.formatList(values.hotelDistanceToSea)]}<br/>'
						+ wl(this.translations.maxCostPerPersonHotel + sep)
						+ ' {[this.showCosts(values.MAXPRICEHOTEL)]}<br/>{[this.showImportantForHotel(values.importantForHotel)]}'
						+ hr;

			hotelsListTmpl = '<div class="request-review-left">'
					+ '<tpl for="hotels">{[xindex === 1 ? "'
					+ wt(this.translations.hotelsOffer + sep, "'") + '" : ""]}'
					+ '<div style="margin: 5px 0;"> - {.}</div></tpl></div>';
		}

		var planesTmpl = '';
		if (this.data.offerForPlanes === 'on') {
			planesTmpl = wrapTitle(this.translations.offerForPlaneForYou)
					+ wl(this.translations.planeFrom + sep) + ' {AIRPORT}<br/>'
					+ wl(this.translations.planeTo + sep)
					+ ' {AIRPORTSARDEGNA}<br/>'
					+ '<div>{[this.showTravelers(values,"plane")]}</div>' + hrc;
		}

		var carsTmpl = '';
		if (this.data.offerForCars === 'on') {
			carsTmpl = wrapTitle(this.translations.offerForCarForYou)
					+ wl(this.translations.carClass + sep) + ' {CARCLASS}<br/>'
					+ wl(this.translations.pickup + sep) + ' {carPickup}<br/>'
					+ wl(this.translations.dropoff + sep)
					+ ' {carDropoff}<br/>'
					+ '{[this.showDriverAge(values.driverAge)]}'
					+ '{[this.showDriverLicense(values.driversLicense)]}<br/>'
					+ '{[this.showDeductible(values.deductible)]}' + hr;
		}

		var ferriesTmpl = '';
		if (this.data.offerForFerries === 'on') {
			ferriesTmpl = wrapTitle(this.translations.offerForFerriesForYou)
					+ wl(this.translations.carType + sep) + ' {CARTYPE}<br/>'
					+ '{[this.showCarMake(values.carmake)]}'
					+ wl(this.translations.carLength + sep)
					+ ' {carlength}<br/>'
					+ wl(this.translations.carWidth + sep) + ' {carwidth}<br/>'
					+ '{[this.showCarHeight(values.carheight)]}'
					+ wl(this.translations.ferryOutgoing + sep)
					+ ' {FERRYROUTEOutgoing}<br/>'
					+ wl(this.translations.ferryReturn + sep)
					+ ' {FERRYROUTEReturn}<br/>'
					+ wl(this.translations.cabinType + sep) + ' {CABINTYPE}'
					+ '<div>{[this.showTravelers(values,"ferry")]}</div>' + hrc;
		}

		this.template = new Ext.XTemplate(
				'<div class="request-review-header">{[this.showSalutationTitle(values.SALUTATION,values.TITLE)]} {firstname} {lastname}<br/>'
						+ this.translations.requestOffer
						+ '</div><br/><div class="clear">'
						+ villasListTmpl
						+ hotelsListTmpl
						+ '</div>'
						+ hrc
						+ this.translations.thankYouText
						+ ' '
						+ Ext.util.Format.date(new Date(), 'd.m.Y')
						+ '. '
						+ this.translations.reviewText
						+ hr
						+ wl(this.translations.travelTime + sep)
						+ ' {[this.showFlexibleDates(values.flexibleDates)]}<br/>'
						+ '<div>'
						+ '<div class="request-review-left">'
						+ wt(this.translations.datesOfTravel)
						+ wl(this.translations.arrivalDate)
						+ ' {arrivalDate}<br/>'
						+ wl(this.translations.departureDate)
						+ ' {departureDate}<br/>'
						+ wl(this.translations.stayLength + sep)
						+ ' {daysCount} {[this.showDaysUnits(values.daysCount)]}</div><div class="request-review-left">'
						+ wt(this.translations.participants)
						+ '{adultsCount} {[this.showAdultsUnits(values.adultsCount)]}<br/>'
						+ '{[this.showChildren(values.childrenCount)]}'
						+ ' {[this.showChildrenAges(values.childrenages)]}'
						+ '{[this.showPet(values.withPet,values.petDescription)]}</div></div>'
						+ hrc
						+ wts(this.translations.region + sep)
						+ ' {[this.formatList(values.region)]}'
						+ hr
						+ villasTmpl
						+ hotelsTmpl
						+ planesTmpl
						+ carsTmpl
						+ ferriesTmpl
						+ '{[this.showSpecialDesires(values.specialDesires)]}'
						+ '<input type="checkbox" value="1" id="request-review-newsletter-checkbox" checked="checked" style="margin-right: 2px;"/>'
						+ this.translations.newsletter + hr
				// + this.translations.footer + hr
				, {
					showSalutationTitle : function(salutation, title) {
						var result = String
								.format('{0} {1}', salutation, title);
						var from = ["Sig. Dott.", "Sig.ra Dott.",
								"Sig. Dott.essa", "Sig.ra Dott.essa",
								"Sig. Avv.", "Sig.ra Avv.", "Sig. Arch.",
								"Sig.ra Arch.", "Sig. Geometra",
								"Sig.ra Geometra", "Sig. Senatore",
								"Sig. Senatore", "Sig. Ing.", "Sig.ra Ing.",
								"Sig. Professore", "Sig.ra Professore"];
						var to = ["Dott.", "Dott.", "Dott.essa", "Dott.essa",
								"Avv.", "Avv.", "Arch.", "Arch.", "Geometra",
								"Geometra", "Senatore", "Senatore", "Ing.",
								"Ing.", "Professore", "Professore"];
						for (var i = 0, len = from.length; i < len; i++) {
							result = result.replace(from[i].toString(), to[i]
											.toString());
						}

						return result;
					},
					showDeductible : function(val) {
						return val > 0
								? trn.withDeductible2
								: trn.withoutDeductible2;
					},
					showBedroomUnits : function(count) {
						return wl(count > 1
								? trn.bedroomUnit
								: trn.bedroomUnit1);
					},
					showBathroomUnits : function(count) {
						return wl(count > 1
								? trn.bathroomUnit
								: trn.bathroomUnit1);
					},
					showAdultsUnits : function(count) {
						return wl(count > 1 ? trn.adultsUnit : trn.adultsUnit1);
					},
					showChildren : function(count) {
						return count > 0 ? String.format('{0} {1}', count,
								wl(count != 1
										? trn.childrenUnit
										: trn.childrenUnit1)) : '';
					},
					showDaysUnits : function(count) {
						return wl(count > 1 ? trn.daysUnit : trn.daysUnit1);
					},
					showPet : function(withPet, desc) {
						return withPet === 'yes' ? String.format('{0} {1}',
								trn.withPet + sep, desc && desc.length
										? desc
										: '') : trn.withoutPet
					},
					showPool : function(withPool) {
						return withPool === 'yes'
								? trn.withPool
								: trn.withoutPool
					},
					showImportantForVilla : function(text) {
						return text && text.length
								? String.format('{0}<br/>{1}',
										wl(trn.importantForVilla), text)
								: ''
					},
					showImportantForHotel : function(text) {
						return text && text.length
								? String.format('{0}<br/>{1}',
										wl(trn.importantForHotel), text)
								: ''
					},
					showRoomCategory : function(roomCategory) {
						return roomCategory && roomCategory.length ? String
								.format('{0} {1}<br/>', wl(trn.roomCategory
												+ sep), roomCategory) : ''
					},
					showDriverAge : function(age) {
						return age && age.length
								? String.format('{0} {1}<br/>',
										wl(trn.driversAge + sep), age)
								: ''
					},
					showDriverLicense : function(val) {
						return val && val.length ? String.format('{0} {1}',
								wl(trn.driversLicense), val === '1'
										? wl(trn.driversLicense3more)
										: wl(trn.driversLicense3less)) : ''
					},
					showFlexibleDates : function(flexibleDates) {
						return flexibleDates === 'yes'
								? trn.flexibleDates
								: trn.fixedDates
					},
					showForChildren : function(forChildren) {
						return forChildren === 'setBed'
								? trn.setBedlc
								: trn.seperateRoomlc
					},
					showRooms : function(hotelRooms) {
						return hotelRooms > 0 ? String.format('{0} {1}<br/>',
								hotelRooms, wl(hotelRooms > 1
										? trn.roomsUnit
										: trn.roomsUnit1)) : ''
					},
					showSpecialDesires : function(specialDesires) {
						return specialDesires && specialDesires.length ? String
								.format(
										'<div class="request-review-header">{0}</div>{1}'
												+ hr,
										wl(trn.yourSpecialDesires),
										specialDesires) : '';
					},
					showCosts : function(costs) {
						return String.format('{0} {1}', costs, costs > 0
										? wl(trn.currencyUnit)
										: '');
					},
					showChildrenAges : function(ages) {
						return ages && ages.length ? String.format(
								'({0} {1})<br/>', this.formatList(ages),
								wl(trn.years)) : '';
					},
					showCarHeight : function(height) {
						return height && height.length ? String
								.format('{0} {1}<br/>',
										wl(trn.carHeight + sep), height) : '';
					},
					showCarMake : function(make) {
						return make && make.length
								? String.format('{0} {1}<br/>', wl(trn.carMake
												+ sep), make)
								: '';
					},
					showAltAirportFrom : function(airport) {
						return airport && airport.length ? String.format(
								'<div style="float:left;">{0}<br/>{1}</div>',
								wl(trn.planeFromAlt), airport) : '';
					},
					showAltAirportTo : function(airport) {
						return airport && airport.length ? String.format(
								'<div style="float:left;">{0}<br/>{1}</div>',
								wl(trn.planeToAlt), airport) : '';
					},
					showTravelers : function(travelers, type) {
						if (travelers) {
							var fname = String.format('{0}_travelerFirstName_',
									type);
							var lname = String.format('{0}_travelerLastName_',
									type);
							var bDate = String.format('{0}_travelerBirthDate_',
									type);
							var selected = String.format(
									'{0}_travelerSelected_', type);
							var result = '';
							for (t in travelers) {
								if (t.indexOf(selected) === 0) {
									var idx = (t.split('_')).length === 3 ? t
											.split('_')[2] : 0;
									if (idx && travelers[t].length) {
										if (result.length === 0)
											result = String
													.format(
															'<div style="clear:both;"><div style="float:left; margin-right: 25px; width: 200px;">{0}</div><div style="float:left;">{1}</div></div>',
															wl(trn.travelerFullName),
															wl(trn.travelerBirthDate));
										result += String
												.format(
														'<div style="clear:both;"><div style="float:left; margin-right: 25px; width: 200px;">{0} {1}</div><div style="float:left;">{2}</div></div>',
														travelers[fname + idx],
														travelers[lname + idx],
														travelers[bDate + idx]);
									}
								}
							}
							return result;
						}
						return '';
					},
					formatList : function(list) {
						if (list === null || list === undefined)
							return '';
						if (!(list instanceof Array))
							list = [list];
						return list.join(', ');
					},
					showHotelsData : function(values) {
						var result = '';
						for (v in values) {
							if (v.indexOf('hotelName') === 0) {
								var hotelID = ((v.split('-')).length === 2) ? v
										.split('-')[1] : 0;
								result += String
										.format(
												'<div style="margin-bottom: 5px;">- {0}<br/>   {1} {2}<br/>   {3} {4}</div>',
												values[v], wl(trn.board + sep),
												this.formatList(values['board_'
														+ hotelID]),
												wl(trn.roomCategory + sep),
												values['roomCategory_'
														+ hotelID]);
							}
						}
						return result;
					}
				});
		if (this.formParams
				&& (this.formParams.villaID || this.formParams.hotelID)) {
			Ext.Ajax.request({
						url : this.url,
						params : {
							cmd : 'getVillasHotelsNames',
							villaID : this.formParams.villaID,
							hotelID : this.formParams.hotelID
						},
						success : this.onShowSuccess,
						failure : this.onFailure,
						scope : this
					});
			this.getComponent('review-content').getEl().update(String.format(
					'<div class="loading-indicator">{0}</div>',
					this.translations.pleaseWait));
			this.enableActions(false);
		} else
			this.template.overwrite(
					this.getComponent('review-content').getEl(), this.data,
					true);
	},
	onChangeRequest : function() {
		var form = Ext.getCmp('requestHolidayRentalCmp');
		if (form) {
			form.show();
			this.hide();
		}
	},
	setFormParams : function(p) {
		this.formParams = p;
	},
	onRequestOffer : function() {
		var wantNewsletter = Ext.get('request-review-newsletter-checkbox');
		if (wantNewsletter && wantNewsletter.dom.checked)
			this.showNewsletterPopup();
		else
			this.sendRequest();
	},
	sendRequest : function() {
		if (this.formParams) {
			this.actions.submit.setText(this.translations.sendingOffer);
			this.actions.submit.disable();
			this.actions.back.disable();

			Ext.Ajax.request({
						url : this.url,
						success : this.onSuccess,
						failure : this.onFailure,
						params : this.formParams,
						scope : this
					});
		}
	},
	onSuccess : function() {
		var thankyou = Ext.getCmp('requestHolidayRentalThankYouPageCmp');
		if (thankyou) {
			thankyou.showPage(this.data, this.translations);
			this.hide();
		}
	},
	onFailure : function(response, request) {
		Ext.ux.RequestHolidayRentalReview.superclass.onFailure.apply(this,
				arguments);
		this.actions.submit.setText(this.translations.requestOffer);
		this.actions.submit.enable();
		this.actions.back.enable();
	},
	onShowSuccess : function(response, request) {
		if (response && response.responseText) {
			var result = Ext.decode(response.responseText, true);
			if (result && result.data)
				Ext.apply(this.data, result.data);
		}
		// console.log(this.data);
		this.template.overwrite(this.getComponent('review-content').getEl(),
				this.data, true);
		this.enableActions(true);
		// console.log(this.data);
	},
	enableActions : function(enable) {
		for (act in this.actions)
			this.actions[act].setDisabled(!enable);
	},
	showNewsletterPopup : function() {
		this.popupWindow = new Ext.Window({
			width : 300,
			height : 100,
			modal : true,
			resizable : false,
			unstyled : true,
			closable : false,
			cls : 'SardegnaForm-popup',
			bodyStyle : {
				padding : '10px'
			},
			items : [{
						xtype : 'box',
						autoEl : {
							html : this.translations.newsletter
						}
					}, {
						xtype : 'box',
						cls : 'SardegnaForm-Spacer'
					}, {
						xtype : 'container',
						defaults : {
							style : {
								'margin-right' : '15px'
							}
						},
						items : [{
							xtype : 'llabel',
							text : this.translations.answerYes,
							listeners : {
								afterrender : {
									fn : function(cmp) {
										cmp.getEl().on({
													click : {
														fn : this.setNewsletterOn,
														scope : this
													}
												});
									},
									scope : this
								}
							}
						}, {
							xtype : 'llabel',
							text : this.translations.answerNo,
							listeners : {
								afterrender : {
									fn : function(cmp) {
										cmp.getEl().on({
													click : {
														fn : this.setNewsletterOff,
														scope : this
													}
												});
									},
									scope : this
								}
							}
						}]
					}]
		});
		this.popupWindow.show();
	},
	closePopupWindow : function() {
		if (this.popupWindow)
			this.popupWindow.close();
	},
	setNewsletterOn : function() {
		this.closePopupWindow();
		if (this.formParams)
			Ext.apply(this.formParams, {
						newsletter : true
					});
		this.sendRequest();
	},
	setNewsletterOff : function() {
		this.closePopupWindow();
		this.sendRequest();
	}
});
Ext.ns('Ext.ux');

Ext.ux.RequestHolidayRentalThankYouPage = Ext.extend(Ext.ux.SardegnaForm, {
	layout : 'fit',
	hidden : true,
	funnels : null,
	translations : {
		requestSent : 'Your request has been successfully sent',
		yourRequest : 'Your request:',
		thankyouFooter : 'request thankyou footer',
		contactFooter : 'request thankyou contact',
		personUnit : 'persons',
		personUnit1 : 'person',
		// villasOffer : 'Villas',
		// hotelsOffer : 'Hotels',
		planesOffer : 'Air fare',
		carsOffer : 'Rental car',
		ferriesOffer : 'Ferry',
		emailText : 'Email',
		forText : 'for'
	},
	createItems : function() {

		Ext.apply(this, {
			items : [{
						itemId : 'thankyou-content',
						xtype : 'box'
					}, {
						itemId : 'google-code-cnt',
						xtype : 'box'
					}]
				/*
				 * , buttons : [{ text : 'back', handler : this.onBack, scope :
				 * this }], buttonAlign : 'left'
				 */
			});

		Ext.ux.RequestHolidayRentalThankYouPage.superclass.createItems.apply(
				this, arguments);
	},
	showPage : function(data, translations) {

		var goalsCompleted = [];
		if (data && data.offerForVillas === 'on')
			goalsCompleted.push('villas');
		if (data && data.offerForHotels === 'on')
			goalsCompleted.push('hotels');

		if (GLOBAL && GLOBAL.funnels && goalsCompleted && goalsCompleted.length) {
			for (fn in GLOBAL.funnels) {
				for (go in goalsCompleted) {
					if (String.format('{0}Goal', goalsCompleted[go]) == fn) {
						for (var i = 0, len = GLOBAL.googleCodes.length; i < len; i++) {
							try {
								var pageTracker = _gat
										._getTracker(GLOBAL.googleCodes[i]);
								pageTracker._trackPageview(GLOBAL.funnels[fn]);
								if (console) {
									try {
										console.log("tracker: "
												+ GLOBAL.googleCodes[i]
												+ "      funnel: "
												+ GLOBAL.funnels[fn]);
									} catch (ex) {
									}
								}
							} catch (ex) {
							}
						}
					}
				}
			}
		}

		this.show();

		if (!this.template) {
			Ext.apply(this.translations, translations);
			var trn = this.translations;
			var sep = ':';

			var villasTmpl = '';
			if (data && data.offerForVillas === 'on') {
				villasTmpl = data.villas && data.villas.length
						? '<tpl for="villas">{[xindex === 1 && xcount > 1 ? "'
								+ this.translations.villasOffer
								+ sep
								+ '<br/>" : ""]}{[xcount > 1 ? " - " : ""]}{.}<br/></tpl><br/>'
						: String.format('{0}<br/><br/>',
								this.translations.villasOffer);
			}

			var hotelsTmpl = '';
			if (data && data.offerForHotels === 'on') {
				hotelsTmpl = data.hotels && data.hotels.length
						? '<tpl for="hotels">{[xindex === 1 && xcount > 1 ? "'
								+ this.translations.hotelsOffer
								+ sep
								+ '<br/>" : ""]}{[xcount > 1 ? " - " : ""]}{.}<br/></tpl><br/>'
						: String.format('{0}<br/><br/>',
								this.translations.hotelsOffer);
			}

			this.template = new Ext.XTemplate(
					'<div class="request-review-header">{[this.showSalutationTitle(values.SALUTATION,values.TITLE)]} {firstname} {lastname} <br/>'
							+ this.translations.requestSent
							+ '</div><div class="request-review-header" style="margin: 20px 0;">'
							+ '{[this.showYourRequest(values.offerForVillas,values.offerForHotels,values.offerForPlanes,values.offerForCars,values.offerForFerries)]}'
							+ '<br/>'
							+ villasTmpl
							+ hotelsTmpl
							+ '{[this.showCars(values.offerForCars, values.CARCLASS)]}'
							+ '{[this.showPlanes(values.offerForPlanes,values)]}'
							+ '{[this.showFerries(values.offerForFerries,values)]}</div><div style="margin: 10px 0;">'
							+ this.translations.thankyouFooter
							+ '</div>'
							+ this.translations.contactFooter
							+ '<br/>'
							+ '<a href="mailto:info@sardegna.de" class="blueArr">'
							+ this.translations.emailText + '</a>', {
						showSalutationTitle : function(salutation, title) {
							var result = String.format('{0} {1}', salutation,
									title);
							var from = ["Sig. Dott.", "Sig.ra Dott.",
									"Sig. Dott.essa", "Sig.ra Dott.essa",
									"Sig. Avv.", "Sig.ra Avv.", "Sig. Arch.",
									"Sig.ra Arch.", "Sig. Geometra",
									"Sig.ra Geometra", "Sig. Senatore",
									"Sig. Senatore", "Sig. Ing.",
									"Sig.ra Ing.", "Sig. Professore",
									"Sig.ra Professore"];
							var to = ["Dott.", "Dott.", "Dott.essa",
									"Dott.essa", "Avv.", "Avv.", "Arch.",
									"Arch.", "Geometra", "Geometra",
									"Senatore", "Senatore", "Ing.", "Ing.",
									"Professore", "Professore"];
							for (var i = 0, len = from.length; i < len; i++) {
								result = result.replace(from[i].toString(),
										to[i].toString());
							}

							return result;
						},
						showPlanes : function(show, values) {
							if (show === 'on') {
								var tt = 0;
								for (v in values)
									if (v.indexOf('plane_travelerSelected_') === 0
											&& values[v].length)
										tt++;
								return String.format(
										'{0}{1} {2} {3} {4}<br/><br/>',
										trn.planesOffer, sep, trn.forText, tt,
										tt == 1
												? trn.personUnit1
												: trn.personUnit);
							}
							return '';
						},
						showCars : function(show, type) {
							return show === 'on' ? String.format(
									'{0}{1} {2}<br/><br/>', trn.carsOffer, sep,
									type) : '';
						},
						showFerries : function(show, values) {
							if (show === 'on') {
								var tt = 0;
								for (v in values)
									if (v.indexOf('ferry_travelerSelected_') === 0
											&& values[v].length)
										tt++;
								return String.format(
										'{0}{1} {2} {3} {4}<br/><br/>',
										trn.ferriesOffer, sep, trn.forText, tt,
										tt == 1
												? trn.personUnit1
												: trn.personUnit);
							}
							return '';
						},
						showYourRequest : function(a, b, c, d, e) {
							return a || b || c || d || e ? trn.yourRequest : '';
						}
					});
		}
		this.template.overwrite(this.getComponent('thankyou-content').getEl(),
				data, true);
		this
				.getComponent('google-code-cnt')
				.getEl()
				.update(
						'<img src="http://www.googleadservices.com/pagead/conversion/1072646207/?value=0&label=default&color=ffffff&format=1&language=en&script=0" />'
						/*
						 * <script type="text/javascript"> \ //<!-- \ var
						 * google_conversion_id = 1072646207; \ var
						 * google_conversion_language = "en"; \ var
						 * google_conversion_format = "1"; \ var
						 * google_conversion_color = "ffffff"; \ var
						 * google_conversion_label = "default"; \ var
						 * google_conversion_value = 0; \ //--> \ </script>
						 * <script type="text/javascript"
						 * src="http://www.googleadservices.com/pagead/conversion.js"></script>
						 */
						, true);
	}/*
		 * , onBack : function() { var review =
		 * Ext.getCmp('requestHolidayRentalReviewCmp'); if (review) {
		 * review.show(); this.hide(); } }
		 */
});
Ext.ns('Ext.ux');
 
Ext.ux.BookHolidayRental = Ext.extend(Ext.ux.SardegnaForm, {
	translations : {
		personalData : 'Personal Data',
		email : 'Your Email',
		salutation : 'Salutation',
		country : 'Country',
		title : 'Title',
		firstName : 'First Name',
		lastName : 'Last Name',
		language : 'Language',
		phone : 'Phone',
		privatePhone : 'private',
		businessPhone : 'business',
		mobilePhone : 'mobile',
		addPhoneNumber : 'Add Phone Number',
		addFaxNumber : 'Add Fax Number',
		addEmail : 'Add Email Address',
		travelerFirstName : 'First name',
		travelerLastName : 'Last name',
		fax : 'Fax number',
		remove : 'Remove',
		additionalEmail : 'Additional email',
		checkingEmail : 'Checking email...',
		address : 'Address',
		zipcode : 'Zip',
		city : 'City',
		pleaseWait : 'Please wait...',
		countryCode : 'Country code',
		areaCode : 'Area code',
		phoneNumber : 'Phone number',
		namesOfTravelers : 'Names and birthdates of travellers',
		travelerBirthDate : 'Date of birth',
		transportation : 'Transportation',
		comments : 'Comments',
		villa : 'Villa',
		hotel : 'Hotel',
		otherVilla : 'If the above choice is not available, I would like the following villa:',
		otherHotel : 'If the above choice is not available, I would like the following hotel:',
		arrivalDate : 'Arrival date',
		departureDate : 'Departure date',
		adults : 'Adults',
		children : 'Children',
		child : 'Child',
		childrenAge : 'Age of children at date of travel',
		continueText : 'Continue',
		sendingBooking : 'Sending booking...'
	},
	offerType : '',
	offerID : 0,
	createItems : function() {
		this.comboWidth = 195;

		this.actions = {
			submit : new Ext.Action({
						text : this.translations.continueText,
						handler : this.onBooking,
						scope : this
					})
		};

		this.transportationField = 'TRANSPORTATION';
		this.transportationStore = this.createStore(this.transportationField);

		this.objectField = this.offerType === 'villa' ? 'VILLA' : 'HOTEL';
		this.objectStore = this.createStoreWithAdditionalValue(
				this.objectField, '');

		this.adultsStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'adults',
								type : 'int'
							}],
					data : this.generateArray(12, 1)
				});

		this.childrenStore = new Ext.data.ArrayStore({
					autoDestroy : true,
					fields : [{
								name : 'children',
								type : 'int'
							}],
					data : this.generateArray(8)
				});

		Ext.apply(Ext.form.VTypes, {
			daterange : function(val, field) {
				var date = field.parseDate(val);

				if (!date) {
					return;
				}
				if (field.startDateField
						&& (!this.dateRangeMax || (date.getTime() != this.dateRangeMax
								.getTime()))) {
					var start = Ext.getCmp(field.startDateField);
					start.setMaxValue(date);
					// start.validate();
					this.dateRangeMax = date;
				} else if (field.endDateField
						&& (!this.dateRangeMin || (date.getTime() != this.dateRangeMin
								.getTime()))) {
					var end = Ext.getCmp(field.endDateField);
					end.setMinValue(date);
					// end.validate();
					this.dateRangeMin = date;
				}

				return true;
			}
		});

		Ext.apply(this, {
			items : [{
						xtype : 'hidden',
						name : 'contactID'
					}, {
						xtype : 'hidden',
						name : 'offerType',
						value : this.offerType === 'villa' ? 'villa' : 'hotel'
					}, {
						xtype : 'hidden',
						name : 'offerID',
						value : this.offerID
					}, {
						xtype : 's-personal-data',
						itemId : 'personal-data',
						translations : this.translations,
						url : this.url,
						listeners : {
							readyForUpdate : function() {
								if (this.loadedData)
									this.getForm().setValues(this.loadedData)

							},
							scope : this
						}
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-combobox',
						fieldLabel : this.translations.transportation,
						mode : 'remote',
						store : this.transportationStore,
						displayField : this.transportationField,
						valueField : this.transportationField + 'ID',
						hiddenName : this.transportationField + 'ID',
						width : this.comboWidth,
						allowBlank : false
					}, {
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : .2
						},
						items : [{
							items : [{
										xtype : 's-datefield',
										fieldLabel : this.translations.arrivalDate,
										vtype : 'daterange',
										id : 'arrivalDate',
										name : 'arrivalDate',
										endDateField : 'departureDate'
									}]
						}, {
							items : [{
										xtype : 's-datefield',
										fieldLabel : this.translations.departureDate,
										vtype : 'daterange',
										id : 'departureDate',
										name : 'departureDate',
										startDateField : 'arrivalDate'
									}]
						}]
					}, {
						xtype : 'container',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form',
							columnWidth : .2
						},
						items : [{
									items : [{
												xtype : 's-combobox',
												name : 'adultsCount',
												fieldLabel : this.translations.adults,
												mode : 'local',
												store : this.adultsStore,
												displayField : 'adults',
												allowBlank : false,
												listeners : {
													select : {
														fn : this.onAdultsSelect,
														scope : this
													}
												},
												width : 78
											}]
								}, {
									items : [{
										xtype : 's-combobox',
										name : 'childrenCount',
										fieldLabel : this.translations.children,
										mode : 'local',
										store : this.childrenStore,
										displayField : 'children',
										allowBlank : false,
										listeners : {
											select : {
												fn : this.onChildrenSelect,
												scope : this
											}
										},
										width : 78
									}]
								}]
					}, {
						xtype : 'container',
						itemId : 'cntOwnerChildrenAge',
						layout : 'column',
						defaults : {
							xtype : 'container',
							layout : 'form'
						},
						items : [{
									columnWidth : .2,
									items : [{
												xtype : 'box',
												autoEl : {
													html : '&nbsp;'
												}
											}]
								}, {
									columnWidth : .8,
									itemId : 'cntChildrenAge',
									defaults : {
										xtype : 'container',
										layout : 'form'
									},
									items : [{
												itemId : 'cntChildrenAgeLabel',
												defaults : {
													xtype : 'label'
												}
											}, {
												itemId : 'cntChildrenAgeBoxes',
												defaults : {
													xtype : 'container',
													layout : 'form',
													defaults : {
														allowBlank : false
													},
													style : {
														'padding-right' : '5px',
														'float' : 'left'
													}
												}
											}]
								}]
					}, {
						xtype : 'hlabel',
						text : this.translations.namesOfTravelers
					}, {
						xtype : 's-travelers-group',
						itemId : 'travelers-data',
						translations : this.translations,
						travelersGroup : 'booking',
						id : 'bookTravelersComponent',
						collapsed : false
					}, {
						xtype : 's-spacer'
					}, {
						xtype : 's-combobox',
						fieldLabel : this.offerType === 'villa'
								? this.translations.villa
								: this.translations.hotel,
						mode : 'remote',
						store : this.objectStore,
						displayField : this.objectField,
						name : this.objectField + '1',
						valueField : this.objectField + 'ID',
						hiddenName : this.objectField + 'ID1',
						tpl : '<tpl for="."><div class="x-combo-list-item">{'
								+ this.objectField
								+ '}<tpl if="xindex === 1">&nbsp;</tpl></div></tpl>',
						width : this.comboWidth
					}, {
						xtype : 's-combobox',
						fieldLabel : this.offerType === 'villa'
								? this.translations.otherVilla
								: this.translations.otherHotel,
						mode : 'remote',
						store : this.objectStore,
						displayField : this.objectField,
						name : this.objectField + '2',
						valueField : this.objectField + 'ID',
						hiddenName : this.objectField + 'ID2',
						tpl : '<tpl for="."><div class="x-combo-list-item">{'
								+ this.objectField
								+ '}<tpl if="xindex === 1">&nbsp;</tpl></div></tpl>',
						width : this.comboWidth
					}, {
						xtype : 's-textarea',
						name : 'comments',
						fieldLabel : this.translations.comments,
						tabIndex : 6000,
						width : 587,
						height : 45
					}],
			buttons : [this.actions.submit],
			buttonAlign : 'right'
		});

		Ext.ux.BookHolidayRental.superclass.createItems.apply(this, arguments);

		this.on({
					afterrender : {
						fn : this.onAfterRender,
						scope : this
					}
				});
	},
	onAfterRender : function() {
		if (this.loadingIndicatorId && Ext.get(this.loadingIndicatorId))
			Ext.get(this.loadingIndicatorId).remove();

		/*
		 * var mask = this.getEl().mask(this.translations.pleaseWait); if
		 * (Ext.isIE6) { this.maskEl = mask; this.task = { run : function() {
		 * this.maskEl.setHeight(this.getEl().getHeight()); }, interval : 250,
		 * scope : this }; Ext.TaskMgr.start(this.task); }
		 */

		this.loadOfferData();
	},
	onBooking : function() {
		if (this.getForm().isValid()) {

			var values = this.getForm().getValues();

			var p = {};
			this.getForm().items.each(function(item) {
						if (item instanceof Ext.form.ComboBox && item.name
								&& item.name.length) {
							p[item.name] = item.getRawValue();
						}
					});
			Ext.applyIf(values, p);

			p = {
				cmd : 'saveBooking',
				isLoggedIn : GLOBAL.isLoggedIn,
				contactsToDelete : this.getPersonalDataCmp()
						.getContactsToDelete()
						|| ''
			};
			Ext.applyIf(p, values);
			
			this.actions.submit.setText(this.translations.sendingBooking);
			this.actions.submit.disable();

			Ext.Ajax.request({
						url : this.url,
						success : this.onSuccess,
						failure : this.onFailure,
						params : p,
						scope : this
					});
		} else {
			var fld = this.getForm().items.find(function(item) {
						return !item.isValid(true);
					});
			if (fld)
				fld.focus();
		}
	},
	onSuccess : function() {
		var thankYouPage = Ext.getCmp('bookHolidayRentalThankYouPageCmp');
		if (thankYouPage) {
			this.hide();
			thankYouPage.show();
		}
	},
	onFailure : function(response, request) {
		Ext.ux.RequestHolidayRentalReview.superclass.onFailure.apply(this,
				arguments);
		this.actions.submit.setText(this.translations.continueText);
		this.actions.submit.enable();
	},
	onAdultsSelect : function(combo, record, index) {
		var count = record instanceof Ext.data.Record
				? record.get('adults')
				: record;
		this.getTravelersCmp().setMaxAdultsTravelers(count);
	},
	onChildrenSelect : function(combo, record, index) {
		var count = record instanceof Ext.data.Record
				? record.get('children')
				: record;
		var cnt = this.getComponent('cntOwnerChildrenAge')
				.getComponent('cntChildrenAge')
				.getComponent('cntChildrenAgeBoxes');
		if (cnt) {
			var cmpArray = cnt.findByType('container');
			Ext.each(cmpArray, function(form, idx, all) {
						var items = form.findByType('combo');
						Ext.each(items, function(field) {
									field.clearInvalid();
								});
					});
			var items = [];
			if (cmpArray.length <= count) {
				for (var i = cmpArray.length; i < count; i++)
					items.push({
								items : [{
									xtype : 's-combobox',
									fieldLabel : String.format('{0} {1}',
											this.translations.child, i + 1),
									mode : 'local',
									store : {
										xtype : 'arraystore',
										autoDestroy : true,
										fields : [{
													name : 'childage',
													type : 'int'
												}],
										data : this.generateArray(18, 1)
									},
									displayField : 'childage',
									name : 'childrenages',
									editable : false,
									width : 70,
									tabIndex : 608
								}]
							});
				cnt.add(items);
			} else {
				for (var i = count; i < cmpArray.length; i++)
					cnt.remove(cmpArray[i], true);
			}
			cnt.doLayout();
		}
		cnt = this.getComponent('cntOwnerChildrenAge')
				.getComponent('cntChildrenAge')
				.getComponent('cntChildrenAgeLabel');
		if (cnt) {
			var cmpArray = cnt.findByType('label');
			if (count && cmpArray.length === 0) {
				cnt.add({
							text : this.translations.childrenAge
						});
				cnt.doLayout();
			} else if (count === 0) {
				cnt.remove(cmpArray[0]);
				cnt.doLayout();
			}
		}
		this.getTravelersCmp().setMaxChildrenTravelers(count);
	},
	loadOfferData : function() {
		this.getForm().load({
			url : this.url,
			params : {
				cmd : 'getOfferData',
				offerID : this.offerID,
				offerType : this.offerType
			},
			success : function(form, action) {
				var data = action.result.data;
				this.loadedData = data;
				this.getPersonalDataCmp().appendContactData(data.emailCounter,
						parseInt(data.phoneCounter) - 1, data.faxCounter);

				this.onChildrenSelect(null, data.childrenCount);
				this.onAdultsSelect(null, data.adultsCount);

				this.fillChildrenAges(data.childrenAges);

				form.setValues(this.loadedData);
				/*
				 * if (data.phoneCounter - 1 > 0) { for (var i = 0; i <
				 * data.phoneCounter - 1; i++) this.onAddPhoneNumber(true); } if
				 * (data.faxCounter > 0) { for (var i = 0; i < data.faxCounter;
				 * i++) this.onAddFaxNumber(true); this.itemsToLoad++; } if
				 * (data.emailCounter > 0) { for (var i = 0; i <
				 * data.emailCounter; i++) this.onAddEmail(true);
				 * this.itemsToLoad++; }
				 */

				// this.itemLoaded();
			},
			failure : function() {
				// this.itemLoaded();
			},
			scope : this
		});
	},
	getTravelersCmp : function() {
		return this.getComponent('travelers-data');
	},
	getPersonalDataCmp : function() {
		return this.getComponent('personal-data');
	},
	fillChildrenAges : function(ages) {
		ages = String.format('{0}', ages).split(',');
		if (ages.length && ages[0] != '') {
			var ii = 0;
			var cnt = this.getComponent('cntOwnerChildrenAge')
					.getComponent('cntChildrenAge')
					.getComponent('cntChildrenAgeBoxes');
			Ext.each(cnt.findByType('combo'), function(combo) {
						if (ii < ages.length) {
							combo.setValue(ages[ii]);
							ii++;
						} else
							return false;
					});
		}
	}
});
Ext.ns('Ext.ux');

Ext.ux.BookHolidayRentalThankYouPage = Ext.extend(Ext.ux.SardegnaForm, {
			layout : 'fit',
			hidden : true,
			translations : {
				confirmation : 'Your booking has been successfully sent'
			},
			pageName : 'book.cfm',
			createItems : function() {
				Ext.apply(this, {
							items : [{
										xtype : 'box',
										autoEl : {
											html : this.translations.confirmation
										}
									}]
						});

				Ext.ux.BookHolidayRentalThankYouPage.superclass.createItems
						.apply(this, arguments);
			}
		});
Ext.onReady(function(){

	//var headerSlidePanels = new SlidePanels();
	//headerSlidePanels.init('user','t','85');
	//headerSlidePanels.slidePanelEvents();
	
	//headerSlidePanels.animationPanel('show');
	
	var headerSlidePanelLogin = new SlidePanels();
	headerSlidePanelLogin.init('login','t');
	headerSlidePanelLogin.slidePanelEvents();
	
});
//set language function
function setLanguage(languageCode) {
	var languagesForm = document.getElementById('languageForm');
	document.getElementById('changeLanguage').value = languageCode;
	languagesForm.submit();
}

//Generate language select
Ext.form.SardinienComboBox = Ext.extend(Ext.form.ComboBox, {
	 	transform: 'lang',
		id: 'lang2',
        width: 72,
		typeAhead: true,
        triggerAction: 'all',
		triggerClass: 'selectTrigger',
		cls: 'selectTextClass',
		listClass: 'selectListClass',
		selectedClass: 'selectSelectedClass',		
        forceSelection: true
});

Ext.onReady(function() {
	//Select
	function setLanguageExt() {
		var languageCode = Ext.get('lang').getValue();
		var languagesForm = document.getElementById('languageForm');
		document.getElementById('changeLanguage').value = languageCode;
		
		var RequestToFileUrl = '/lib/services/service.cfm';
		
		Ext.Ajax.request({
		    form: languagesForm,
			url:RequestToFileUrl,
			params: {cmd: 'changeLanguage'},
			success: function(response, opts) {
				var responseObj = Ext.decode(response.responseText);
				window.location = responseObj.link;
				//window.location.reload();
		   },
		   failure: function(response, opts) {
		      alert('server-side failure with status code ' + response.status);
		   },
		   scope: this
		});
		
		//languagesForm.submit();
	}

	var convertedLang = new Ext.form.SardinienComboBox();
	convertedLang.on('select', setLanguageExt);
	
	
	checkHeightMenuAndContainer();

});

function setMenuClickedCookie(menuItem) {
	//Ext.util.Cookies.set('MAINMENUCLICKEDITEM', menuItem);
	//var cookie = new Ext.state.CookieProvider();
	//cookie.set('MAINMENUCLICKEDITEM', menuItem);
	createCookie('MAINMENUCLICKEDITEM', menuItem);
}

function checkHeightMenuAndContainer() {
	var mainMenu =  Ext.get('mainMenu');
	var detailsContent =  Ext.get('detailsContent');
	
	if(mainMenu != null && detailsContent != null){
		var mainMenuHeight = mainMenu.getHeight()+13;
		var detailsContentHeight = detailsContent.getHeight();
		
		if(detailsContentHeight < mainMenuHeight){
			detailsContent.setStyle('min-height', mainMenuHeight+23+'px');
		}
	}
}function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/*
JAVASCRIPT LIBRARY FILE: popup window
 
All material herein (c) Copyright 2003 Binary Minds, Inc.              
All Rights Reserved.
 
**Document Under Development**
Current Administrator: Tom
 
Changes (incl. date and name)
7/25/03 Tom: created
 
Required Parameters: 
					sURL - url of the target page
					
Optional Parameters: 
					sName - name of the page
					iWidth - integer width
					iHeight - integer height
					sScrollbars - yes/no
					sStatus - yes/no
					sResize - yes,no
					sToolbar - yes,no 

Usage:
winOpen('pageName.htm','winName',300,200,null,'yes')
*/
var pop = null;


function openwindow(sURL,sName,iWidth,iHeight,sScrollbars,sStatus,sResize,sToolbar,iCentered){
var sFeatures;
var sPosition;

if(arguments.length >= 2)
	sName = arguments[1];
else 
	sName = " ";
	
if(arguments.length >= 3)
	sPosition = ",width=" + arguments[2] + ",height=" + arguments[3];
else 
	sPosition = "";
	
if(arguments.length >= 5)
	sScrollbars = arguments[4];

else
	sScrollbars = "auto";

if(arguments.length >= 6)
	sStatus = arguments[5];
else
	sStatus = "yes";

if(arguments.length >= 7)
	sResize = arguments[6];
else
	sResize = "yes";
	
if(arguments.length >= 8)
	sToolbar = arguments[7];
else
	sToolbar = "no";	

if(arguments.length >= 9)
	sCentered = arguments[8];
else
	sCentered = "0";	
	
sFeatures = "resizable="+sResize+",status="+sStatus+",toolbar="+sToolbar+",scrollbars="+sScrollbars+sPosition;	
pop = window.open(sURL,sName,sFeatures);
if(sCentered == 1) {
	pop.moveTo((parseInt((screen.width-arguments[2])*0.5)),(parseInt((screen.height-arguments[3])*0.5)));
}
pop.focus();
pop.opener = self;
self.name = "main";
}