﻿/// <reference path="mootools-1.2.3-core.js" />
/// <reference path="mootools-1.2.3.1-more.js" />


var LT;
if (!LT)
    LT = {};

LT.ComInfo = new Class({
    initialize: function(op) {
        this.options = $extend({
            OutBox: '',
            DetailBox: '',
            ItemBox: ''
        }, op || {});

        this.Container = $(this.options.OutBox);
        this.DetailBox = $(this.options.DetailBox);
        this.Items = [];

        // $$('#' + this.options.OutBox + ' .' +
        // this.options.ItemBox)
        this.Container.getElements('.' + this.options.ItemBox).each(
				function(tab) {
				    var com = this.Parse(tab);
				    this.Items.include(com);

				    tab.addEvent('mouseover', function() {
				        this.Show(com);
				    } .bind(this));

				} .bind(this));

        if (this.Items.length > 0)
            this.Show(this.Items[0]);

    },
    Show: function(com) {
        if (com) {
            this.DetailBox.getElement('img.photo')
					.setProperty('src', com.Photo);
            this.DetailBox.getElement('a.title').setProperties({
                'title': com.Title,
                'href': com.Link
            });
            this.DetailBox.getElement('a.title').innerHTML = com.Title;
            this.DetailBox.getElement('.intro').innerHTML = com.Intro;
            this.DetailBox.getElement('a.detail').setProperty('href', com.Link);
        }
    },
    Parse: function(tab) {
        var com = {};
        com.Title = tab.getElement('a.title').getProperty('title');
        com.Link = tab.getElement('a.title').getProperty('href');
        com.Photo = tab.getElement('img.photo').getProperty('src');
        com.Intro = tab.getElement('.intro').innerHTML;
        return com;
    }

});


var MooSlide = new Class({

    initialize: function(params) {
        this.items = params.items;
        this.mode = params.mode || 'horizontal';
        this.modes = { horizontal: ['left', 'width'], vertical: ['top', 'height'] };
        this.size = params.size || 240;
        this.box = params.box.setStyle(this.modes[this.mode][1], (this.size * this.items.length) + 'px');
        this.button_event = params.button_event || 'click';
        this.handle_event = params.handle_event || 'click';
        this.onWalk = params.onWalk || null;
        this.currentIndex = null;
        this.previousIndex = null;
        this.nextIndex = null;
        this.interval = params.interval || 5000;
        this.autoPlay = params.autoPlay || false;
        this._play = null;
        this.handles = params.handles || null;
        if (this.handles) {
            this.addHandleButtons(this.handles);
        }
        this.buttons = {
            previous: [],
            next: [],
            play: [],
            playback: [],
            stop: []
        };
        if (params.addButtons) {
            for (var action in params.addButtons) {
                this.addActionButtons(action, $type(params.addButtons[action]) == 'array' ? params.addButtons[action] : [params.addButtons[action]]);
            }
        }
        this.fx = new Fx.Tween(this.box, $extend((params.fxOptions || { duration: 500, wait: false }), { property: this.modes[this.mode][0] }));
        this.walk((params.startItem || 0), true, true);
    },

    addHandleButtons: function(handles) {
        for (var i = 0; i < handles.length; i++) {
            handles[i].addEvent(this.handle_event, this.walk.bind(this, [i, true]));
        }
    },

    addActionButtons: function(action, buttons) {
        for (var i = 0; i < buttons.length; i++) {
            switch (action) {
                case 'previous': buttons[i].addEvent(this.button_event, this.previous.bind(this, [true])); break;
                case 'next': buttons[i].addEvent(this.button_event, this.next.bind(this, [true])); break;
                case 'play': buttons[i].addEvent(this.button_event, this.play.bind(this, [this.interval, 'next', false])); break;
                case 'playback': buttons[i].addEvent(this.button_event, this.play.bind(this, [this.interval, 'previous', false])); break;
                case 'stop': buttons[i].addEvent(this.button_event, this.stop.bind(this)); break;
            }
            this.buttons[action].push(buttons[i]);
        }
    },

    previous: function(manual) {
        this.walk((this.currentIndex > 0 ? this.currentIndex - 1 : this.items.length - 1), manual);
    },

    next: function(manual) {
        this.walk((this.currentIndex < this.items.length - 1 ? this.currentIndex + 1 : 0), manual);
    },

    play: function(interval, direction, wait) {
        this.stop();
        if (!wait) {
            this[direction](false);
        }
        this._play = this[direction].periodical(interval, this, [false]);
    },

    stop: function() {
        $clear(this._play);
    },

    walk: function(item, manual, noFx) {
        if (item != this.currentIndex) {
            this.currentIndex = item;
            this.previousIndex = this.currentIndex + (this.currentIndex > 0 ? -1 : this.items.length - 1);
            this.nextIndex = this.currentIndex + (this.currentIndex < this.items.length - 1 ? 1 : 1 - this.items.length);
            if (manual) {
                this.stop();
            }
            if (noFx) {
                this.fx.cancel().set((this.size * -this.currentIndex) + 'px');
            } else {
                this.fx.start(this.size * -this.currentIndex);
            }
            if (manual && this.autoPlay) {
                this.play(this.interval, 'next', true);
            }
            if (this.onWalk) {
                this.onWalk((this.items[this.currentIndex] || null), (this.handles && this.handles[this.currentIndex] ? this.handles[this.currentIndex] : null));
            }
        }
    }

});



var MooTabs = new Class({

    initialize: function(element, options) {
        this.options = $extend({
            mouseOverClass: 'focus',
            mouseOutClass: 'normal'
        }, options || {});

        this.el = $(element);
        this.elid = element;


        this.titles = $$('#' + this.elid + ' .' + this.options.mouseOverClass, '#' + this.elid + ' .' + this.options.mouseOutClass);
        this.defaultTab = this.titles.filter('.' + this.options.mouseOverClass)[0];
        if (!this.defaultTab) {
            this.defaultTab = this.titles[0];
            this.defaultTab.addClass(this.options.mouseOverClass);
        }
        this.activeTitle = this.defaultTab;



        this.panels = [];
        this.titles.each(function(item) {


            var panel = $(item.title);
            if (panel) this.panels.include(panel);


            item.addEvent('mouseover', function() {
                if (item != this.activeTitle) {
                    item.addClass(this.options.mouseOverClass);
                    item.removeClass(this.options.mouseOutClass);
                    this.activate(item);
                }
            } .bind(this));

            item.addEvent('mouseout', function() {
                if (item != this.activeTitle) {
                    item.addClass(this.options.mouseOutClass);
                    item.removeClass(this.options.mouseOverClass);
                }
            } .bind(this));
        } .bind(this));

        this.activate(this.activeTitle);

    },

    activate: function(tab) {
        if ($type(tab) == 'string') {
            myTab = $$('#' + this.elid + ' .' + this.options.mouseOverClass, '#' + this.elid + ' .' + this.options.mouseOutClass).filter('[title=' + tab + ']')[0];
            tab = myTab;
        }

        if ($type(tab) == 'element') {
            var newTab = tab.getProperty('title');
            this.panels.each(function(panel) { panel.setStyle('display', 'none'); });
            try {
                $(newTab).setStyle('display', '');


                if (this.options.OnChange) {
                    this.options.OnChange($(newTab).getElement('.ComInfo'));
                }
            } catch (e) { };


            this.titles.addClass(this.options.mouseOutClass);
            this.titles.removeClass(this.options.mouseOverClass);

            tab.addClass(this.options.mouseOverClass);
            tab.removeClass(this.options.mouseOutClass);

            this.activeTitle = tab;


        }
    }

});



/*************************************************************/

var noobSlide = new Class({

    initialize: function(params) {
        this.items = params.items;
        this.mode = params.mode || 'horizontal';
        this.modes = { horizontal: ['left', 'width'], vertical: ['top', 'height'] };
        this.size = params.size || 240;
        this.box = params.box.setStyle(this.modes[this.mode][1], (this.size * this.items.length) + 'px');
        this.button_event = params.button_event || 'click';
        this.handle_event = params.handle_event || 'click';
        this.onWalk = params.onWalk || null;
        this.currentIndex = null;
        this.previousIndex = null;
        this.nextIndex = null;
        this.interval = params.interval || 5000;
        this.autoPlay = params.autoPlay || false;
        this._play = null;
        this.handles = params.handles || null;
        if (this.handles) {
            this.addHandleButtons(this.handles);
        }
        this.buttons = {
            previous: [],
            next: [],
            play: [],
            playback: [],
            stop: []
        };
        if (params.addButtons) {
            for (var action in params.addButtons) {
                this.addActionButtons(action, $type(params.addButtons[action]) == 'array' ? params.addButtons[action] : [params.addButtons[action]]);
            }
        }
        this.fx = new Fx.Tween(this.box, $extend((params.fxOptions || { duration: 500, wait: false }), { property: this.modes[this.mode][0] }));
        this.walk((params.startItem || 0), true, true);
    },

    addHandleButtons: function(handles) {
        for (var i = 0; i < handles.length; i++) {
            handles[i].addEvent(this.handle_event, this.walk.bind(this, [i, true]));
        }
    },

    addActionButtons: function(action, buttons) {
        for (var i = 0; i < buttons.length; i++) {
            switch (action) {
                case 'previous': buttons[i].addEvent(this.button_event, this.previous.bind(this, [true])); break;
                case 'next': buttons[i].addEvent(this.button_event, this.next.bind(this, [true])); break;
                case 'play': buttons[i].addEvent(this.button_event, this.play.bind(this, [this.interval, 'next', false])); break;
                case 'playback': buttons[i].addEvent(this.button_event, this.play.bind(this, [this.interval, 'previous', false])); break;
                case 'stop': buttons[i].addEvent(this.button_event, this.stop.bind(this)); break;
            }
            this.buttons[action].push(buttons[i]);
        }
    },

    previous: function(manual) {
        this.walk((this.currentIndex > 0 ? this.currentIndex - 1 : this.items.length - 1), manual);
    },

    next: function(manual) {
        this.walk((this.currentIndex < this.items.length - 1 ? this.currentIndex + 1 : 0), manual);
    },

    play: function(interval, direction, wait) {
        this.stop();
        if (!wait) {
            this[direction](false);
        }
        this._play = this[direction].periodical(interval, this, [false]);
    },

    stop: function() {
        $clear(this._play);
    },

    walk: function(item, manual, noFx) {
        if (item != this.currentIndex) {
            this.currentIndex = item;
            this.previousIndex = this.currentIndex + (this.currentIndex > 0 ? -1 : this.items.length - 1);
            this.nextIndex = this.currentIndex + (this.currentIndex < this.items.length - 1 ? 1 : 1 - this.items.length);
            if (manual) {
                this.stop();
            }
            if (noFx) {
                this.fx.cancel().set((this.size * -this.currentIndex) + 'px');
            } else {
                this.fx.start(this.size * -this.currentIndex);
            }
            if (manual && this.autoPlay) {
                this.play(this.interval, 'next', true);
            }
            if (this.onWalk) {
                this.onWalk((this.items[this.currentIndex] || null), (this.handles && this.handles[this.currentIndex] ? this.handles[this.currentIndex] : null));
            }
        }
    }

});



/*************************************************************/



LT.Compare = new Class({
    div: null,
    item: new Hash(),
    Max: 4,
    Template: '',
    Container: '',
    initialize: function(div) {
        this.div = $(div);
        if (arguments[1])
            this.Template = arguments[1];
        if (arguments[2])
            this.Container = arguments[2];
        this.Read();
        this.Show();
    },
    Add: function(id, title) {
        if (this.item.getLength() < this.Max) {
            if (this.item.has(id)) {
                alert('该酒店已在列表中');
            } else {
                this.item.set(id, title);
                this.Save();
                this.Show();
            }
        } else {
            alert('最多可添加' + this.Max + '家酒店');
        }
    },
    Remove: function(id) {
        if (this.item.has(id)) {
            this.item.erase(id);
        }
        this.Save();
        this.Show();
    },
    RemoveAll: function() {
        this.item.empty();
        Cookie.dispose('COMP');
        this.Show();
    },
    Save: function() {
        Cookie.write('COMP', JSON.encode(this.item));
    },
    Read: function() {
        try {
            this.item = new Hash(JSON.decode(Cookie.read('COMP')));
        } catch (e) {
        }
    },
    Show: function() {
        var html = '';
        var _self = this;
        this.item.each(function(val, key) {
            html += _self.Template.replace(/{VALUE}/g, val)
									.replace(/{KEY}/g, key);
        });
        this.div.innerHTML = this.Container.replace(/{CONTENT}/g, html);
    },
    Go: function(url) {
        if (this.item.getLength() > 1) {
            window.open(url + this.item.getKeys().join(','));
        } else {
            alert('至少选择2家以上酒店方可进行比较');
        }
    }
});



/*************************************************************/


LT.FloatDiv = new Class({
    el: null,
    size: null,
    top: null,
    left: null,
    initialize: function(obj) {
        var _self = this;
        this.el = $(obj);
        this.size = this.el.getSize();
        this.top = $(document.body).getSize().y
						+ $(document.body).scrollTop;
        this.left = $(document.body).getSize().x;
        this.el.setStyles({
            'top': [this.top - this.size.y, this.top],
            'left': this.left
        });
        window.addEvent('scroll', function() {
            var win = $(document.body);
            _self.top = win.getSize().y + win.scrollTop;
            _self.el.setStyles({
                'top': _self.top - _self.size.y
            });
        });
    },
    Show: function() {
        new Fx.Morph(this.el, {
            duration: 300,
            transition: Fx.Transitions.Sine.easeInOut
        }).start({
            'left': this.left - this.size.x
        });
    },
    Hide: function() {
        var _self = this;
        new Fx.Morph(this.el, {
            duration: 300,
            transition: Fx.Transitions.Sine.easeInOut
        }).start({
            'left': this.left - 22
        });
    }
});




/**************************************************/


LT.QuickBox = new Class({


    Implements: Options,

    options: {
        resizeDuration: 600,
        resizeTransition: Fx.Transitions.Circ.easeOut,
        initialWidth: 250,
        initialHeight: 250,
        padding: 10,
        animateCaption: true,
        counter: "Image {NUM} of {TOTAL}",
        anchorName: "quickbox"
    },

    initialize: function(options) {


        this.setOptions(options);
        this.anchors = $$("a[rel=" + this.options.anchorName + "]");
        this.anchors.each(function(a) {
            a.store("caption", a.get("title") || a.getElement("img").get("alt"));
            a.addEvent("click", this.open.bindWithEvent(this, a));
        }, this);


        this.overlay = new Element("div", {
            id: "qbOverlay",
            events: {
                click: this.close.bindWithEvent(this)
            }
        }).inject(document.body, "top");

        this.quickBox = new Element("div", {
            id: "qbBox",
            styles: {
                width: this.options.initialWidth,
                height: this.options.initialHeight,
                marginLeft: -(this.options.initialWidth / 2),
                position: "absolute"
            }
        }).inject(document.body, "top");

        this.prevLink = new Element("a", { id: "qbPrev", href: "#" }).inject(this.quickBox);
        this.nextLink = this.prevLink.clone().setProperty("id", "qbNext").injectInside(this.quickBox);

        this.stage = new Element("div", { id: "qbStage" }).inject(this.quickBox);

        this.prevLink.addEvent("click", this.changeImage.bindWithEvent(this, -1));
        this.nextLink.addEvent("click", this.changeImage.bindWithEvent(this, 1));

        this.bottom = new Element("div", { id: "qbBottom" }).inject(this.quickBox);

        this.closeButton = new Element("div", {
            id: "qbClose",
            events: {
                click: this.close.bindWithEvent(this)
            }
        }).inject(this.bottom);

        this.caption = new Element("div", { id: "qbCaption" }).inject(this.bottom);
        this.counter = new Element("div", { id: "qbCounter" }).inject(this.bottom);

        var nextEffect = this.nextEffect.bind(this);

        this.fx = {
            overlay: new Fx.Tween(this.overlay, {
                property: "opacity"
            }),
            resize: new Fx.Morph(this.quickBox, {
                duration: this.options.resizeDuration,
                transition: this.options.resizeTransition,
                onComplete: nextEffect
            }),

            show: new Fx.Tween(this.stage, {
                property: "opacity",
                onComplete: nextEffect
            }),
            bottom: new Fx.Tween(this.bottom, {
                property: "top",
                duration: 400,
                onComplete: nextEffect
            })
        };

        this.active = false;
        document.addEvent("mousewheel", this.mouseWheelListener.bindWithEvent(this));
        document.addEvent("keydown", this.keyboardListener.bindWithEvent(this));

    },

    open: function(event, link) {

        this.active = true;

        var size = window.getSize();
        var scroll = window.getScroll();
        var scrollSize = window.getScrollSize();

        /* The images should be 640x480(max). They're easily clipped at 1024x768,
        * so we get them as close as possible to the top of the window. */
        var offset = Math.round((size.y < 768) ? size.y / 36 : size.y / 10);

        var top = scroll.y + offset;

        this.overlay.setStyles({
            opacity: 0,
            display: "block",
            width: scrollSize.x,
            height: scrollSize.y
        });
        this.quickBox.setStyles({
            display: "block",
            top: top
        });
        this.fx.overlay.start(0.8);
        this.startLoad(link);
        return false;
    },

    startLoad: function(link, preload) {

        if (!link) return;
        var image = new Asset.image(link.get("href"), {
            onload: function() {
                if (!preload && this.currentLink == link) this.nextEffect();
            } .bind(this)
        });
        if (!preload) {
            this.stage.addClass("loading");
            this.stage.setStyle("display", "block");
            this.stage.empty();
            this.bottom.setStyle("opacity", 0);
            this.prevLink.setStyle("display", "none");
            this.nextLink.setStyle("display", "none");
            this.currentLink = link;
            this.currentCaption = link.retrieve("caption");
            this.currentImage = image;
            this.currentIndex = this.anchors.indexOf(link);
            this.step = 1;
        }
    },

    keyboardListener: function(event) {
        if (!this.active) return;
        if (event.key != "f5") event.preventDefault();
        switch (event.key) {
            case "esc": case "x": case "q": this.close(); break;
            case "b": case "p": case "left": this.changeImage(event, -1); break;
            case "f": case "n": case "right": this.changeImage(event, 1);
        }
    },


    mouseWheelListener: function(event) {
        if (!this.active) return;
        if (event.wheel > 0) this.changeImage(event, -1);
        if (event.wheel < 0) this.changeImage(event, 1);
    },

    changeImage: function(event, step) {

        event.preventDefault();
        var link = this.anchors[this.currentIndex + step];
        if (!link) return false;
        for (var f in this.fx) this.fx[f].cancel();
        this.startLoad(link);
    },

    nextEffect: function() {

        switch (this.step++) {

            case 1:
                var w = this.currentImage.width + this.options.padding * 2;
                var h = this.currentImage.height + this.options.padding * 2;
                this.prevLink.setStyle("height", h);
                this.nextLink.setStyle("height", h);
                this.fx.resize.start({
                    width: w,
                    height: h,
                    marginLeft: -(this.currentImage.width / 2)
                });
                break;
            case 2:

                this.stage.removeClass("loading");
                this.stage.setStyle("opacity", 0);
                this.currentImage.setStyle("margin", this.options.padding);
                this.currentImage.inject(this.stage);
                this.fx.show.start(1);
                break;
            case 3:

                this.prevLink.setStyle("display", "block");
                this.nextLink.setStyle("display", "block");
                if (this.options.animateCaption) {
                    if (this.options.counter) {
                        var total = this.anchors.length;
                        var num = this.currentIndex + 1;
                        var counterText = this.options.counter;
                        counterText = counterText.replace(/\{NUM\}/, num);
                        counterText = counterText.replace(/\{TOTAL\}/, total);
                        this.counter.set("text", counterText);
                    }
                    this.caption.set("text", this.currentCaption);
                    var height = this.bottom.getStyle("height").toInt();
                    this.bottom.setStyles({
                        opacity: 1,
                        top: -height
                    });
                    this.fx.bottom.start(0);
                }
                break;
            case 4:
                this.startLoad(this.anchors[this.currentIndex - 1], true);
                this.startLoad(this.anchors[this.currentIndex + 1], true);
                break;
        }
    },

    close: function() {
        this.quickBox.setStyle("display", "none");
        this.overlay.fade("out");
        this.active = false;
    }
});


LT.Map = new Class({
    map: null,
    initialize: function(op) {
        this.options = $extend({
            Canvas: $('map_canvas'),
            City: '青岛市',
            Address: '',
            Position: null,
            Title: ''
        }, op || {});
        // initialize MAP handler

        this.map = new google.maps.Map2(this.options.Canvas);
        this.map.addControl(new google.maps.SmallMapControl());
        this.Go();
    },
    Go: function() {
        if (this.options.Position) {
            var p = new google.maps.LatLng(this.options.Position.x,
							this.options.Position.y);
            this.map.setCenter(p, 17);
            this.SetMarker(p);
        } else {
            var addr = this.options.Address;
            if (addr.indexOf(this.options.City, 0) < 0)
                addr = this.options.City + addr;
            var geocoder = new google.maps.ClientGeocoder();
            var _self = this;
            geocoder.getLatLng(addr, function(p) {
                if (!p) {
                    _self.ShowError('无法识别地址“'
											+ _self.options.Address + '”');
                } else {
                    _self.map.setCenter(p, 17);
                    _self.SetMarker(p);
                }
            });
        }
    },

    SetMarker: function(p) {
        var marker = new google.maps.Marker(p, {
            title: this.options.Title, autoPan: true
        });
        this.map.addOverlay(marker);
        marker.openInfoWindowHtml(this.Tip());
    },
    ShowError: function(msg) {
        var geo = new google.maps.ClientGeocoder();
        var _self = this;
        geo.getLatLng(this.options.City, function(p) {
            if (p) {
                _self.map.setCenter(p, 10);
                var marker = new google.maps.Marker(p, {
                    title: '错误'
                });
                _self.map.addOverlay(marker);
                marker.openInfoWindowHtml(msg);
            }
        });
    },
    Tip: function() {
        var html = '';
        html += '<h3>' + this.options.Title + '</h3>';
        html += '<p>地址：' + this.options.Address + '</p>';
        return html;
    }

});


LT.Page = {
    QuickSearch: function() {
        var area = $('QuickArea');
        var key = $('QuickKeyword');
        if (area.value == area.title) area.value = "";
        if (key.value == key.title) key.value = "";
        if (area.value == "" && key.value == "") {
            area.select();
            alert("请输入搜索条件！");
        } else {
            var qs = new Hash({ Area: area.value == area.title ? '' : area.value, Keyword: key.value == key.title ? "" : key.value });
            window.location = "/Search/?" + qs.toQueryString();
        }
    },
    CompanySearch: function() {
        var qs = new Hash();
        if ($('SearchName').value.length > 0 && $('SearchName').value != $('SearchName').title) qs.set('Name', $('SearchName').value);
        if ($('SearchRegion').value.length > 0) qs.set('Area', $('SearchRegion').value);
        if ($('SearchRegion').options[$('SearchRegion').selectedIndex].value.length > 0) qs.set('Region', $('SearchRegion').options[$('SearchRegion').selectedIndex].value);
        if ($('SearchCuisine').options[$('SearchCuisine').selectedIndex].value.length > 0) qs.set('CuisineCode', $('SearchCuisine').options[$('SearchCuisine').selectedIndex].value);
        if ($('SearchAgio').options[$('SearchAgio').selectedIndex].value.length > 0) qs.set('Agio', $('SearchAgio').options[$('SearchAgio').selectedIndex].value);
        if ($('SearchCost').options[$('SearchCost').selectedIndex].value.length > 0) qs.set('Cost', $('SearchCost').options[$('SearchCost').selectedIndex].value);
        window.location = "/Search/?" + qs.toQueryString();
    }
}


LT.DropMenu = new Class({
    initialize: function() {
        this.options = $extend({
            handle: null,
            context: null
        }, arguments[0] || {});
        
        this.PositionContext();
        this.options.handle.addEvent('click', function() { this.options.context.setStyle('visibility', 'visible'); } .bind(this));
        this.options.handle.addEvent('blur', function() { setTimeout(function(){this.options.context.setStyle('visibility', 'hidden'); }.bind(this),400)} .bind(this));

    },
    PositionContext: function() {
        var p = this.options.handle.getPosition();
        var s = this.options.handle.getSize();
        var cs = this.options.context.getSize();

        p.x -= (cs.x - s.x) / 2;
        p.y += s.y + 1;
        this.options.context.setPosition(p);
    }

});