﻿var GalleryHelper = {
    Reset: function() {
        GalleryHelper.CurrentGallery.hideVideo();
    }
}

var Gallery = new Class({
    currentImage: -1,
    audioPlaying: false,
    options: {
        captions: false,
        showNav: false
    },
    initialize: function(container, options) {

        if (options != null)
            this.options = options;

        this.container = $$(container);
        if (this.container.length > 0) {
            this.img = $$(container + ' img');
            this.img.set('tween', { duration: '1000', transition: 'sine:in' });

            this.img.setOpacity(0);
            this.img.setStyle('visibility', 'hidden');
            this.img.removeClass('hidden');

            if (this.options.captions) {
                this.container.addEvent('mouseover', this.ShowCaption.bind(this));
                this.container.addEvent('mouseout', this.HideCaption.bind(this));
                this.Caption = new Element('div', {
                    'class': 'caption'
                });
                this.Caption.setOpacity(0);
                this.CaptionText = new Element('span');
                this.CaptionText.inject(this.Caption);
                this.Caption.inject(this.container[0], 'bottom');
            }

            if (this.options.showNav || this.options.showPageCount) {

                var video = $$(container + ' .video')
                var audio = $$(container + ' .audio')
                var gmap = $$(container + ' #gmapgallery');
                if (this.img.length > 1 || video.length > 0 || audio.length > 0 || gmap.length > 0) {
                    this.Nav = new Element('div', { 'class': 'gallerynav' });
                    this.Nav.setOpacity(0);
                    this.Nav.inject(this.container[0], 'bottom');

                    if (this.options.showNav) {
                        this.NavEl = new Element('span', { 'class': 'nav' });
                        this.NavEl.inject(this.Nav);

                        this.NavLeft = new Element('img', { 'src': 'images/navleft.png' });
                        this.NavLeft.inject(this.NavEl);
                        this.NavLeft.addEvent('click', this.doLeftNav.bind(this));

                        this.NavPause = new Element('img', { 'src': 'images/navpause.png' });
                        this.NavPause.inject(this.NavEl);
                        this.NavPause.addEvent('click', this.PauseImage.bind(this));

                        this.NavRight = new Element('img', { 'src': 'images/navright.png' });
                        this.NavRight.inject(this.NavEl);
                        this.NavRight.addEvent('click', this.doRightNav.bind(this));
                    }
                    if (this.options.showPageCount) {
                        this.PageSummary = new Element('span', { 'class': 'page' });
                        this.PageSummary.inject(this.Nav)
                    }


                    if (video.length > 0 || audio.length > 0 || gmap.length > 0) {

                        this.MediaContainer = new Element('span', { 'class': 'media' });
                        this.MediaContainer.inject(this.Nav);

                        this.Media = new Element('ul');
                        this.Media.inject(this.MediaContainer);

                        if (gmap.length > 0) {
                            var v = new Element('li');
                            v.inject(this.Media);
                            this.MapLink = new Element('a', { 'href': '#', 'html': 'Map' });
                            this.MapLink.inject(v);
                            this.MapLink.addEvent('click', this.showMap.bind(this));
                            gmap.setStyle('display', 'none');

                        }
                        if (video.length > 0) {
                            var v = new Element('li');
                            v.inject(this.Media);
                            this.VideoLink = new Element('a', { 'href': '#', 'html': 'Video' });
                            this.VideoLink.inject(v);
                            this.VideoLink.addEvent('click', this.showVideo.bind(this));
                            video.setStyle('display', 'none');
                        }
                        if (audio.length > 0) {
                            var a = new Element('li');
                            a.inject(this.Media);
                            this.AudioLink = new Element('a', { 'href': '#', 'html': 'Audio' });
                            this.AudioLink.inject(a);
                            this.AudioLink.addEvent('click', this.toggleAudio.bind(this));
                            audio.setStyle('display', 'none');
                        }

                    }
                    this.Nav.fade(1);
                }

            }



            if (this.img.length > 0) {

                this.NextImage();
                this.PlayImage();
            }
        }

    },
    hide: function() {
        this.img.addClass('hidden');
        if (this.Caption != null)
            this.Caption.addClass('hidden');
    },
    InitMap: function() {
        if (GBrowserIsCompatible()) {
            if (this.map == null) {
                this.mapDiv = $('gmapgallery');
                this.map = new GMap2(this.mapDiv);
                this.map.setCenter(new GLatLng(1, 1), 1);
                this.map.addMapType(G_PHYSICAL_MAP);
                this.map.addControl(new GMenuMapTypeControl());
                this.map.addControl(new GSmallZoomControl());
                this.map.enableScrollWheelZoom();
                var req = new Request({ url: 'map/', onComplete: this.PlotPoints.bind(this) }).post();
                var mapNav = new Element('div', { 'id': 'galleryreturn' });
                mapNav.inject($('gmapgallery'));
                mapNav.set('html', "Return to slideshow");
                mapNav.addEvent('click', this.hideVideo.bind(this));

                this.map.tooltip = new Element('div', { 'class': 'tooltip' });
                this.map.getPane(G_MAP_FLOAT_PANE).appendChild(this.map.tooltip);
                this.map.tooltip.setOpacity(0);
            }

        }
    },
    PlotPoints: function(r) {
        var sections = r.split('|');
        var points = sections[0].split(',');
        var lat = points[0] * 1;
        var lng = points[1] * 1;
        var zoom = points[2] * 1;
        this.map.setCenter(new GLatLng(lng, lat), zoom);

        this.tinyIcon = new google.maps.Icon();
        var tinyIcon = this.tinyIcon;
        tinyIcon.image = "http://seasonsnew.strattons.com/images/map_pointer.png";
        tinyIcon.shadow = "http://seasonsnew.strattons.com/images/map_shadow.png";
        tinyIcon.iconSize = new google.maps.Size(12, 20);
        tinyIcon.shadowSize = new google.maps.Size(22, 20);
        tinyIcon.iconAnchor = new google.maps.Point(6, 20);
        tinyIcon.tooltipAnchor = new google.maps.Point(4, 8);
        tinyIcon.infoWindowAnchor = new google.maps.Point(5, 1);

        this.markerOptions = { icon: tinyIcon };

        if (this.mapDiv.hasClass('hotel')) {
            var type = points[3] * 1;

            switch (type) {
                case 1:

                    var hotelX = points[4] * 1;
                    var hotelY = points[5] * 1;
                    var ll = new google.maps.LatLng(hotelY, hotelX);
                    this.map.setCenter(ll);
                    var GM = new google.maps.Marker(ll, this.markerOptions);
                    this.map.addOverlay(GM);

                    break;
                case 2:
                case 3:
                    var bounds = new google.maps.LatLngBounds;
                    var ll = new Array();

                    var m = this;

                    for (var x = 1; x <= sections.length - 1; x++) {
                        var point = sections[x].split(',');
                        ll[x - 1] = new google.maps.LatLng(point[1], point[0]);

                        var GM = new google.maps.Marker(ll[x - 1], this.markerOptions);
                        GM.tooltip = point[2];
                        google.maps.Event.addListener(GM, 'mouseover', function() { m.showTooltip(this) });
                        google.maps.Event.addListener(GM, 'mouseout', function() { m.map.tooltip.fade(0); });
                        this.map.addOverlay(GM);
                        bounds.extend(ll[x - 1]);
                    }


                    if (type == 3) {

                        directions = new GDirections();

                        directions.loadFromWaypoints(ll, { getPolyline: true });
                        google.maps.Event.addListener(directions, 'load', function(d) {

                            var poly = directions.getPolyline();
                            m.map.addOverlay(poly);
                        });

                    }
                    this.map.setCenter(bounds.getCenter());
                    this.map.setZoom(this.map.getBoundsZoomLevel(bounds));
                    break;
            }
        }
        else {
            var num = points[3] * 1;
            for (var i = 1; i <= num; i++) {
                var pointers = sections[i].split(',');


                var pLat = pointers[0] * 1;
                var pLng = pointers[1] * 1;
                var pText = pointers[2];
                var pUrl = pointers[3];

                this.AddPoint(pLat, pLng, pText, pUrl);

            }
        }
    },
    AddPoint: function(pLat, pLng, pText, pUrl) {

        var ll = new google.maps.LatLng(pLng, pLat);
        var GM = new google.maps.Marker(ll, this.markerOptions);
        GM.tooltip = unescape(pText);

        GM.link = unescape(pUrl);

        this.map.addOverlay(GM);
        GEvent.addListener(GM, "click", function(o) {
            location.href = unescape(GM.link);
        });

        var mp = this;
        google.maps.Event.addListener(GM, 'mouseover', function() { mp.showTooltip(this) });
        google.maps.Event.addListener(GM, 'mouseout', function() { mp.map.tooltip.fade(0); });

    },
    showTooltip: function(marker) {
        this.map.tooltip.set('html', marker.tooltip);

        $$('#gmapgallery div div')[0].setStyle('z-index', '');
        this.map.tooltip.getParent().setStyle('z-index', '507');

        this.map.tooltip.setStyle('width', 'auto');
        this.map.tooltip.setStyle('white-space', 'nowrap');
        var size = this.map.tooltip.getSize();

        this.map.tooltip.setStyle('width', size.x > 100 ? '100px' : 'auto');
        this.map.tooltip.setStyle('white-space', size.x > 100 ? 'normal' : 'nowrap');
        var point = this.map.getCurrentMapType().getProjection().fromLatLngToPixel(this.map.fromDivPixelToLatLng(new GPoint(0, 0), true), this.map.getZoom());
        var offset = this.map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), this.map.getZoom());
        var anchor = marker.getIcon().tooltipAnchor;
        var width = marker.getIcon().iconSize.width;
        var height = this.map.tooltip.clientHeight;


        var pos = new google.maps.ControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y - anchor.y - height));
        pos.apply(this.map.tooltip);

        this.map.tooltip.fade(0.8);
    },
    showMap: function(e) {
        e.stop();
        $('gmapgallery').setStyle('display', '');
        $$('.gallerynav').addClass('hidden');
        this.InitMap();
        this.PauseImage();
        this.img.addClass('hidden');

    },
    setVideo: function(state) {
        var video = this.container.getElements('.video');
        video.each(function(v) {
            v.setStyle('display', state);
        });
    },
    setAudio: function(state) {
        var audio = this.container.getElements('.audio');
        audio.each(function(a) {
            a.setStyle('display', state);
        });
    },
    showVideo: function(e) {
        this.img.addClass('hidden');
        so.write('videoDiv');
        if (GalleryHelper.CurrentGallery != null)
            GalleryHelper.Reset();

        this.stopAudio();

        this.setVideo('');
        this.PauseImage();

        GalleryHelper.CurrentGallery = this;

        e.stop();
    },
    hideVideo: function() {

        GalleryHelper.CurrentGallery = null;
        if ($('gmapgallery') != null)
            $('gmapgallery').setStyle('display', 'none');


        this.PlayImage();

        this.img.removeClass('hidden');

        if ($('videoDiv') != null) {
            this.setVideo('none');
            $('videoDiv').empty();
        }
        if ($('gmapgallery') != null) {
            $('gmapgallery').empty();
            this.map = null;
        }
        $$('.gallerynav').removeClass('hidden');
    },
    toggleAudio: function(e) {

        if (this.audioPlaying) {
            this.stopAudio();

        }
        else {
            this.showAudio();

        }
        e.stop();
    },
    stopAudio: function() {
        if (this.AudioLink != null) {
            $('audioDiv').empty();
            this.setAudio('none');
            this.AudioLink.set('html', 'Audio');
            this.AudioLink.removeClass('playing');
            this.audioPlaying = false;
        }
    },
    showAudio: function() {
        this.setAudio('');
        aso.write('audioDiv');
        this.AudioLink.set('html', 'Stop Playing');
        this.AudioLink.addClass('playing');
        this.audioPlaying = true;
    },
    doRightNav: function() {
        this.setVideo('none');
        this.PauseImage();
        this.NextImage();
        this.PlayImage();
    },
    doLeftNav: function() {
        this.setVideo('none');
        this.PauseImage();
        this.PrevImage();
        this.PlayImage();
    },
    NextImage: function() {
        if (this.currentImage >= 0) {
            this.img[this.currentImage].fade(0);
        }
        this.currentImage++;

        if (this.currentImage >= this.img.length)
            this.currentImage = 0;

        this.img[this.currentImage].fade(1);
        this.SetCaption();
    },
    PrevImage: function() {
        this.img[this.currentImage].fade(0);
        this.currentImage--;

        if (this.currentImage < 0)
            this.currentImage = this.img.length - 1;

        this.img[this.currentImage].fade(1);
        this.SetCaption();
    },
    PlayImage: function() {
        if (this.img.length > 1)
            this.Cycle = this.NextImage.periodical(6000, this);
    },
    PauseImage: function() {
        $clear(this.Cycle);
    },
    SetCaption: function() {
        if (this.PageSummary != null) {
            this.PageSummary.set('html', (this.currentImage + 1) + ' of ' + this.img.length);
        }
        if (this.Caption != null) {
            this.CaptionText.set('html', this.img[this.currentImage].getProperty('title'));
        }
    },
    ShowCaption: function() {
        this.Caption.fade('in');
    },
    HideCaption: function() {
        this.Caption.fade('out');
    }
}
);

var Dropdown = new Class({
    initialize: function() {
        this.Dropdowns = $$('.dropdown a');
        var y = this.OpenMenu.bind(this);
        var x = this.StartClose.bind(this);
        this.Dropdowns.each(function(e) {
            e.addEvent('mouseover', y.pass(e));
            e.addEvent('mouseout', x.pass(e));
        })
    },
    OpenMenu: function(e) {
        $clear(this.timeout);

        var parent = e.getParent().getParent();
        parent.getElements('a').each(function(k) {

            if (k.hasClass('open') && k != e) {
                k.removeClass('open');
                k.getParent().getElements('ul').each(function(i) {
                    i.setStyle('display', 'none');
                });
            }
        }
                );

        if (!e.hasClass('open')) {
            e.addClass('open');

            if (e.getParent().getChildren().length > 1) {

                var children = e.getParent().getChildren()[1];
                children.setOpacity(0);
                children.setStyles({ 'display': 'block' });
                children.fade(1);


                var height = children.getSize().y;
                var top = -(height / 2) + e.getPosition().y;

                if (!parent.hasClass('dropdown') && top + height > parent.getPosition().y + parent.getSize().y)
                    top = parent.getPosition().y + parent.getSize().y - height;

                if (!parent.hasClass('dropdown') && top < parent.getPosition().y)
                    top = parent.getPosition().y;

                if (top + height > $('pagebody').getSize().y) {
                        top = parent.getPosition().y + parent.getSize().y - height;
                }
                
                var only = e.getParent().getElements('ul li:only-child');
                if (only[0] == e.getParent().getElements('li')[0]) {
                    top = e.getParent().getPosition().y;
                }

                if (top < 120)
                    top = 120;

                top = top - parent.getPosition().y;
                children.setStyle('top', top + 'px');

            }
        }
    },
    StartClose: function(e) {
        this.timeout = this.CloseMenu.delay(500);
    },
    CloseMenu: function() {
        $clear(this.timeout);

        $$('.dropdown ul').each(function(i) {
            i.fade(0);
            i.getParent().getElements('a').removeClass('open');
        });

    }
});


/*
Function: $get
This function provides access to the "get" variable scope + the element anchor

Version: 1.3

Arguments:
key - string; optional; the parameter key to search for in the url's query string (can also be "#" for the element anchor)
url - url; optional; the url to check for "key" in, location.href is default

Example:
>$get("foo","http://example.com/?foo=bar"); //returns "bar"
>$get("foo"); //returns the value of the "foo" variable if it's present in the current url(location.href)
>$get("#","http://example.com/#moo"); //returns "moo"
>$get("#"); //returns the element anchor if any, but from the current url (location.href)
>$get(,"http://example.com/?foo=bar&bar=foo"); //returns {foo:'bar',bar:'foo'}
>$get(,"http://example.com/?foo=bar&bar=foo#moo"); //returns {foo:'bar',bar:'foo',hash:'moo'}
>$get(); //returns same as above, but from the current url (location.href)
>$get("?"); //returns the query string (without ? and element anchor) from the current url (location.href)

Returns:
Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
Returns "" if the variable is not present in the given query string

Credits:
Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url]
Function by Jens Anders Bakke, webfreak.no
*/
function $get(key, url) {
    if (arguments.length < 2) url = location.href;
    if (arguments.length > 0 && key != "") {
        if (key == "#") {
            var regex = new RegExp("[#]([^$]*)");
        } else if (key == "?") {
            var regex = new RegExp("[?]([^#$]*)");
        } else {
            var regex = new RegExp("[?&]" + key + "=([^&#]*)");
        }
        var results = regex.exec(url);
        return (results == null) ? "" : results[1];
    } else {
        url = url.split("?");
        var results = {};
        if (url.length > 1) {
            url = url[1].split("#");
            if (url.length > 1) results["hash"] = url[1];
            url[0].split("&").each(function(item, index) {
                item = item.split("=");
                results[item[0]] = item[1];
            });
        }
        return results;
    }
}
