var SSAA = SSAA || {};
jQuery(function () {
    SSAA.site.initialize();
    SSAA.mapwidget.initialize();
});

SSAA.site = (function ($) {
    var that = {};

    /* public functions */
    that.initialize = function () {
        createDialog();
        makeDirectionLinksModal();
        initializeSlideShow();
        initializeDirections();
    };

    /* private functions */

    function initializeSlideShow() {
        $images = $('#headline div.images');
        if ($images.length) {
            $images.cycle({
                fx: 'fade',
                timeout: 10000,  // transition every 10 seconds
                speed: 1000      // spend 1 second doing the transition
            });
        }
    };
    function makeDirectionLinksModal() {
       $('a.map').click(function() {
           var $dialog = SSAA.site.$dialog;
           $dialog.html('Loading directions...').dialog('open');
           var href = $(this).attr('href').replace('#', ' #');
           $dialog.load(href, initializeDirections);
           return false;
       })
    }

    function initializeDirections() {
        var $wrapper = $('#directionsmap'),
            map, latitude, longitude;
        if ($wrapper.length && GBrowserIsCompatible()) {

                // $wrapper.find('.canvas') returns jQuery... use the [0] 
                // subscript to get the actual HTML element for Google to use
                map       = new GMap2($wrapper.find('.canvas')[0]);

                // find the latitude and longitude inputs inside the wrapper
                latitude  = $wrapper.find('input[name="lat"]').val();
                longitude = $wrapper.find('input[name="long"]').val();
                resortname = $wrapper.find('input[name="resortname"]').val();
                
            // normal gmap initialization
            map.setCenter(new GLatLng(latitude, longitude), 13);
            map.setUIToDefault();
            var point = new GLatLng(latitude, longitude);
            var marker = createAdvancedMapMarker(point,'Directions', resortname);
            map.addOverlay(marker);
        }
    }
    
    
    function createAdvancedMapMarker(point,name,html) {
        var marker = new GMarker(point);

        // The info window to show onClick
        html = '<b>' + html + '</b>' + 
         '<br />Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
         '<input type="text" SIZE="40" name="saddr" id="saddr" value="" /><br />' +
         '<INPUT value="Get Directions" TYPE="SUBMIT">' +
         '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + '"/>';

        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(html);
        });
        return marker;
    }

    function createDialog() {
        if ($("#dialog").size() == 0) {
            $("body").append("<div id='dialog' style='font-size: smaller;'></div>");
        }
        that.$dialog = $('#dialog');
        that.$dialog.dialog({
            autoOpen: false,
            bgiframe: true,
            modal: true,
            draggable: false,
            resizable: false,
            // if position changed to center and you update content of dialog
            // you have to close / open the dialog to re-center
            position: 'top',
            width: 600
        });
    };


    return that;
}(jQuery));

SSAA.mapwidget = (function ($) {
    var that = {};

    that.ids = {
        list : 'resort-list-',
        pins : 'pushpin-',
        imgs : 'resort-img-'
    };

    /* public functions */
    that.initialize = function () {
        if ($('#state-map').length > 0) {
            initializeTooltips();
            handleClicks();
            startSlideShow();
        }
    };

    that.nextResort = function () {
        var $next = $('#resort-list li.active + li');
        if ($next.length == 0) {
            $next = $('#resort-list li:first');
        }
        var resort = parseAbbrev($next.attr('id'));
        highlightResort(resort);
    };


    /* private functions */
    function startSlideShow() {
        that.interval = setInterval(function() { that.nextResort() }, 15000);
        $resortlist = $('#resort-list li')
        var ranNum = Math.floor(Math.random() * $resortlist.length);
        highlightResort(parseAbbrev($resortlist.get(ranNum).id));
    };

    function handleClicks() {
        $('#resort-list li, span.pushpin').click(function(ev) {
            var resort = parseAbbrev($(this).attr('id'));
            highlightResort(resort);
            clearInterval(that.interval);
            return false;
        });
    };

    function highlightResort(resort) {
        $('#resort-list li.active').removeClass('active');
        $('span.pushpin.active').removeClass('active');
        $('img.resort-highlight.active').removeClass('active').hide();
        /* resort list */
        $('#'+ that.ids.list + resort).addClass('active');
        /* resort pin */
        $('#'+ that.ids.pins + resort).addClass('active');
        $('#'+ that.ids.pins + resort).trigger('pushpinshow');
        /* resort image */
        $('#'+ that.ids.imgs + resort).addClass('active').show();
    };

    function parseAbbrev(id) {
        var lastDash = id.lastIndexOf('-');
        return id.substring(lastDash+1, id.length);
    }

    function initializeTooltips() {
        $('span.pushpin').qtip({
            content: false, // pull from alt attribute
            style: {
                tip: 'topMiddle'
            },
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            },
            show: {
                delay: 0,
                when: 'pushpinshow',
                solo: true
            },
            hide: {
                when: 'pushpinhide'
            },
        });
    };

    return that;
}(jQuery));
