var BrowseHotels = new Class({
    Implements: [Options, Events],
    options:
    {
        container: '',
        url: '',
        hotelList: [],
        isIE6: /msie|MSIE 6/.test(navigator.userAgent),
        flashId: '',
        flashObj: null,
        popupW: 288,
        popupH: 190
    },
    initialize: function(options)
    {
        this.setOptions(options);
        this._init();
        this._initPopup();
        
        new Request.JSON({
            url: this.options.url,
            onComplete: function(response)
            {
                if(response)
                {
                    this.options.hotelList = response.list;
                    this._initListing();
                    this._preloadImages();
                    
                }
            }.bind(this)
        }).post();
        
        this.fadeIn = new Fx.Morph('hotelPopupContent', {duration: 700, transition: Fx.Transitions.Sine.easeOut});
        
        this.openEffect = new Fx.Morph('hotelPopup', {duration: 700, transition: Fx.Transitions.Sine.easeOut,
            onComplete: function()
            {
                this.fadeIn.start({opacity: 1});
                /*if(this.options.isIE6)
                {
                    $('hotelPopupFrame').setStyles({
                        left: $('hotelPopup').getPosition().x,
                        top: $('hotelPopup').getPosition().y,
                        display: 'inline'
                    });
                }*/
            }.bind(this)
        });
        this.closeEffect = new Fx.Morph('hotelPopup', {duration: 700, transition: Fx.Transitions.Sine.easeOut,
            onStart: function()
            {
                /*if(this.options.isIE6)
                {
                    $('hotelPopupFrame').setStyles({
                        left: $('hotelPopup').getPosition().x,
                        top: $('hotelPopup').getPosition().y,
                        display: 'none'
                    });
                }*/
            }.bind(this)
        });
    },
    _init: function()
    {
        var container = $(this.options.container);
        new Element('div', {
            id: 'browseHotelBtn',
            html: 'BROWSE OUR HOTELS', 
            styles:
            {
              textAlign: 'right',
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: 770,
              height: 25,
              zIndex: 3,
              backgroundColor: '#fff',
              opacity: .5,
              color: '#000',
              lineHeight: 25,
              paddingRight: 16,
              fontSize: 11,
              opacity: 0,
              cursor: 'pointer'
            },
            events:
            {
                click: function()
                {
                    this.getFlash(this.options.flashId).setBusy(true);
                    this._showHotels();
                }.bind(this)
            }
        }).inject(container).fade(0.5);
    },
    
    _initListing: function()
    {
        var container = $(this.options.container);
        var div = new Element('div', {
            id: 'browseHotelsBG',
            styles:
            {
                width: container.getWidth(),
                height: container.getHeight(),
                position: 'absolute',
                left: 0,
                top: 0,
                backgroundColor: '#f0f0f0',
                opacity: 0,
                zIndex: 99
            }
        }).inject(container);
        
        new Element('div', {
            text: 'CLOSE X',
            styles:
            {
                position: 'absolute',
                right: 5,
                top: 5,
                color: '#333',
                cursor: 'pointer',
                fontSize: 10
            },
            events:
            {
                click: function()
                {
                    this.getFlash(this.options.flashId).setBusy(false);
                    this._hideHotels();
                }.bind(this)
            }
        }).inject(div);
        
        var table = new Element('table', {
            cellpadding: 0,
            cellspacing: 0,
            border: 0,
            styles: 
            {
                width: container.getWidth(),
                height: container.getHeight(),
                padding: 10
            }
        }).inject(div);
        var tbody = new Element('tbody').inject(table);
        var tr = new Element('tr').inject(tbody);
        var td = new Element('td', {styles:{textAlign: 'left', verticalAlign: 'top'}}).inject(tr);
        
        var cell = new Element('div', {
            styles:
            {
                padding: 10
            }
        }).inject(td);
        var cellH = container.getHeight() - 40;
        
        
        
        for(var i = 0; i < this.options.hotelList.length; i++)
        {
            var item = this.options.hotelList[i];
            
            if(cell.getHeight() >= cellH)
            {
                td = new Element('td', {styles:{textAlign: 'left', verticalAlign: 'top'}}).inject(tr);
                cell = new Element('div', {styles:{padding: 10}}).inject(td);
            }
            

            var temp = new Element('div').inject(cell);
            var span = new Element('span', {styles:{}}).inject(temp);
            var tempName = item.name;
            
            
            if(item.region)
            {
                var nameArray = tempName.split(' ');
                
                if(nameArray.length >= 3)
                {
                    tempName = "";
                    nameArray.each(function(item, index){
                        if(index != 0 && index % 2 == 0)
                            tempName += '<br/>';
                        tempName += item;
                        if(index + 1 < nameArray.length)
                            tempName += ' ';
                    });
                }
                tempName = '<a href="'+ item.url +'">'+ tempName +'</a>';
                temp.addClass('hotel-region');
                //set the html
                span.set('html', tempName);
                
            }
            else if(item.area)
            {
                temp.addClass('hotel-area');
                //set the html
                span.set('html', tempName);
            }
            else
            {
                span.addClass('hotel-name');
                var link = new Element('a', {
                    href: item.url,
                    html: item.areaname == '' ? tempName : tempName,
                    img: item.image,
                    extra: item.styles,
                    address: item.address,
                    phone: item.phone,
                    reservation_code: item.reservation_code,
                    rating: item.rating
                }).inject(span);
                
                if(item.areaname != "")
                {
                    new Element('div', {
                        styles:
                        {
                            fontSize: 10,
                            color: '#333'
                        },
                        html: '(' + item.areaname + ')'
                    }).inject(span);
                }
                
                if(item.image != "")
                {
                    link.addEvents({
                        mouseover: function(e)
                        {
                            if(this.fadeOutTimer)
                                $clear(this.fadeOutTimer);
                        
                            var evt = new Event(e);
                            evt.target.addClass('hotel-on');
                            var container = $(this.options.container);
                            var popup = $('hotelPopup');
                            
                            var realX = evt.target.getPosition().x - container.getPosition().x;
                            var realY = evt.target.getPosition().y - container.getPosition().y;
                            
                            var tempX = container.getWidth() - (realX + evt.target.getWidth() + this.options.popupW);
                            var tempY = container.getHeight() - (realY + this.options.popupH);
                            
                            //console.log('x: ' + tempX + ' - y: ' + tempY);
                            
                            if(tempX >= 0)
                            {
                                popup.setStyle('left', evt.target.getPosition().x + evt.target.getWidth());
                                //right
                            }
                            else
                            {
                                popup.setStyle('left', (evt.target.getPosition().x - this.options.popupW));
                                //left
                            }
                            
                            if(tempY >= 0)
                            {
                                popup.setStyle('top', evt.target.getPosition().y);
                                //bottom
                            }
                            else
                            {
                                //top
                                popup.setStyle('top', evt.target.getPosition().y + evt.target.getHeight() - this.options.popupH);
                            }
                            
                            var content = $('hotelPopupContent');
                            
                            if(tempX > 0 && tempY < 0)
                            {
                                popup.setStyle('background', this.options.isIE6 ? '#fff' : 'url(/img/home/home_new/popup_bottom_left.png) no-repeat top left');
                                content.setStyle('padding', this.options.isIE6 ? '10px 0px 0px 10px' : '9px 0px 0px 28px');
                            }
                            else if(tempX > 0 && tempY >= 0)
                            {
                                popup.setStyle('background', this.options.isIE6 ? '#fff' : 'url(/img/home/home_new/popup_top_left.png) no-repeat top left');
                                content.setStyle('padding', this.options.isIE6 ? '10px 0px 0px 10px' : '9px 0px 0px 28px');
                            }
                            else if(tempX < 0 && tempY < 0)
                            {
                                popup.setStyle('background', this.options.isIE6 ? '#fff' : 'url(/img/home/home_new/popup_bottom_right.png) no-repeat top left');
                                content.setStyle('padding', this.options.isIE6 ? '10px 0px 0px 10px' : '9px 0px 0px 10px');
                            }
                            else if(tempX < 0 && tempY > 0)
                            {
                                popup.setStyle('background', this.options.isIE6 ? '#fff' : 'url(/img/home/home_new/popup_top_right.png) no-repeat top left');
                                content.setStyle('padding', this.options.isIE6 ? '10px 0px 0px 10px' : '9px 0px 0px 10px');
                            }    
                            
                            
                            content.empty();
                            
                            //hotel image and stars
                            var imageContainer = new Element('div', {
                                html: '<img src="'+evt.target.get('img')+'" width="250" height="100">',
                                styles:
                                {
                                    position: 'relative',
                                    width: 250
                                }
                            }).inject(content);
                            
                            var stars = '';
                            var isHalf = String(evt.target.get('rating')).indexOf(".") < 0 ? false : true;
                            var length = parseInt(evt.target.get('rating'));
                            for(var j = 0; j < length; j++)
                                stars += '<img src="/img/home/home_new/star.png" class="pngfix" width="17" height="16" />';
                            stars += isHalf ? '<img src="/img/home/home_new/star_half.png" class="pngfix" width="17" height="16" />' : ''
                            new Element('div', {
                                html: stars,
                                styles:
                                {
                                    width: 248,
                                    height: 16,
                                    position: 'absolute',
                                    left: 0,
                                    bottom: 0,
                                    padding: '0 4px 2px 0',
                                    textAlign: 'right'
                                }
                            }).inject(imageContainer);
                            
                            
                            var styles = evt.target.get('extra');
                            var tempS = styles ? styles.split(' ') : [];
                            styles = this._toUpperCase(tempS, ' ');
                            tempS = styles.split('&amp;');
                            styles = this._toUpperCase(tempS, '&');
                            
                            //text
                            new Element('div', {
                                styles: 
                                {
                                    color: '#000',
                                    textAlign: 'left',
                                    padding: '3px 0 0 1px'
                                },
                                html: '<span style="color: #1a4390">' + styles + '</span><br/>' + 
                                      '<div style="font-size:10px;">' + evt.target.get('address') + '</div>' +
                                      '<div style="font-size:10px;">' + evt.target.get('phone') +'</div>'
                                      
                                      //'<div style="font-size:10px;overflow:hidden;width:240px;height:15px;">' + evt.target.get('address') + '</div>' +
                                      //'<div style="font-size:10px;overflow:hidden;width:240px;height:15px;">' + evt.target.get('phone') +'</div>'
                            }).inject(content);
                            
                            
                            this.closeEffect.cancel();
                            this.openEffect.start({
                                width: [popup.getWidth(), this.options.isIE6 ? 270 : this.options.popupW],
                                height: [popup.getHeight(), this.options.isIE6 ? this.options.popupH - 4 : this.options.popupH]
                            });
                            
                            //buttons
                            new Element('div', {
                                html: '<a href="https://booking.ihotelier.com/istay/istay.jsp?PortalSymbol=JDV&languageid=1&HotelID='+ evt.target.get('reservation_code') +'"><img src="/img/home/home_new/booknow.gif" width="72" height="20" border="0" /></a> <a href="'+evt.target.get('href')+'"><img src="/img/home/home_new/learnmore.gif" width="72" height="20" border="0" /></a>',
                                styles:
                                {
                                    textAlign: 'center',
                                    paddingTop: '4px',
                                    width: this.options.popupW - 40
                                }
                            }).inject(content);
                            
                        }.bind(this),
                        mouseout: function(e)
                        {
                            e.target.removeClass('hotel-on');
                            this.fadeOutTimer = this._hidePopup.delay(700, this);
                        }.bind(this)
                    });
                }
            }
            
                
            if(i + 1 < this.options.hotelList.length)
            {
                var nextItem = this.options.hotelList[i + 1];
                if(nextItem.region || nextItem.area)
                    temp.setStyle('padding-bottom', '10px');
                else
                    temp.setStyle('padding-bottom', '2px');
            }                           
        }                
        
    },
    
    _hidePopup: function(e)
    {
        this.fadeIn.cancel();
        $('hotelPopupContent').setStyle('opacity', 0);
        var popup = $('hotelPopup');
        this.openEffect.cancel();
        this.closeEffect.start({
            width: [popup.getWidth(), 0],
            height: [popup.getHeight(), 0]
        });
    },
    
    _initPopup: function()
    {
        var container = $(document.body);
        var div =  new Element('div', {
            id: 'hotelPopup',
            styles:
            {
                width: 0,
                height: 0,
                backgroundColor: '#fff',
                position: 'absolute',
                left: 0,
                top: 0,
                zIndex: 1000
            }
        }).inject(container);
        
        
        var content = new Element('div', {
            id: 'hotelPopupContent',
            styles:
            {
                width: this.options.popupW,
                height: this.options.popupH,
                position: 'absolute',
                left: 0,
                top: 0,
                zIndex: 1002,
                opacity: 0,
                textAlign: 'left'
            },
            events:
            {
                mouseenter: function(e)
                {
                    if(this.fadeOutTimer)
                        $clear(this.fadeOutTimer);
                }.bind(this),
                mouseleave: function()
                {
                    this.fadeOutTimer = this._hidePopup.delay(1500, this);
                }.bind(this)
            }
            
        }).inject(div);
        
        /*if(this.options.isIE6)
        {
            new Element('iframe', {
                id: 'hotelPopupFrame',
                styles:
                {
                    width: 288,
                    height: 236,
                    position: 'absolute',
                    left: 0,
                    top: 0,
                    display: 'none',
                    zIndex: 999
                }
            }).inject(container);
            
        }*/
        
    },
    
    _preloadImages: function()
    {
        var imgs = new Array();
        imgs.push("/img/home/home_new/popup_bottom_left.png");
        imgs.push("/img/home/home_new/popup_top_left.png");
        imgs.push("/img/home/home_new/popup_bottom_right.png");
        imgs.push("/img/home/home_new/popup_top_right.png");
        imgs.push("/img/home/home_new/star.png");
        imgs.push("/img/home/home_new/star_half.png");
        
        this.options.hotelList.each(function(item){
            
            if(item.image)
                imgs.push(item.image)
        });
        new Asset.images(imgs, {
            onComplete: function(){
            }
        });
    },
    
    _showHotels: function()
    {
        $('browseHotelsBG').fade(0.9);
    },
    
    _hideHotels: function()
    {
        $('browseHotelsBG').fade(0);
    },
    
    _toUpperCase: function(array, separator)
    {
        var str = "";
        array.each(function(item, i){
            str += item.substring(0, 1).toUpperCase() + item.substring(1, item.length);
            if(i + 1 < array.length)
                str += separator;
        });
        return str;
    },
    
    getFlash: function(name)
    {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[name];
        }
        else {
            return document[name];
        }

    },
    showBrowse: function()
    {
        $('browseHotelBtn').setStyle('display', 'inline');
    },
    hideBrowse: function()
    {
        $('browseHotelBtn').setStyle('display', 'none');
    }
});

window.addEvent('domready', function(){
    browseHotel = new BrowseHotels({
        container: 'flashContainer',
        url: '/services/hotel_list',
        flashId: 'homeHeader'
    });
});  


function showBrowse()
{
    browseHotel.showBrowse();
}

function hideBrowse()
{
    browseHotel.hideBrowse();
}
