

// =================
// = jGrowl config =
// =================
$.jGrowl.defaults.position = 'center'


// ================
// = Flash config =
// ================
var swfparams = {
	menu: "false",
	wmode: "transparent"
};

// ===========
// = Globals =
// ===========
var map_icons
var Favorites = null

var POS = (function() {
    
    var icons = false
    
    function iconFactory(imgpath, size, anchorPos) {
        var icon = new GIcon()
        size = size || [12, 16]
        anchorPos = anchorPos || [6, 16]
        // icon.iconSize = new GSize(16, 16);
        // icon.iconAnchor = new GPoint(8, 16);
        icon.iconSize = new GSize(size[0], size[1]);
        icon.iconAnchor = new GPoint(anchorPos[0], anchorPos[1]);        
        icon.image = imgpath        
        return icon
    }
    
    function initIcons() {
        // icons
        // var hotel = new GIcon()
        // hotel.iconSize = new GSize(17, 27);
        // hotel.shadowSize = new GSize(22, 20);
        // hotel.iconAnchor = new GPoint(8, 27);
        // hotel.infoWindowAnchor = new GPoint(5, 1);
        // hotel.image = "/img/map/markers/hotel.png"
        

        var hotel = iconFactory("/img/map/markers/green.gif")
        var area = iconFactory("/img/map/markers/information.png", [16, 16], [8, 16])
        var destination = iconFactory("/img/map/markers/blue.gif")        
        var sailingTrip = iconFactory("/img/map/markers/red.gif")
        var channelTrip = iconFactory("/img/map/markers/orange.gif")        
        var race = iconFactory("/img/map/markers/yellow.gif")



        icons = {
            'Hotel': hotel,
            'Area': area,
            'Destination': destination,
            'SailingTrip': sailingTrip,
            'ChannelTrip': channelTrip,
            'default': area
        }
    }
    
    function panAndZoom(map, point, zoom) {
        map.panTo(point);           
        window.setTimeout(function() {
            map.setZoom(Math.min(10, zoom));                 
        }, 700)
    }
    
    function zoomAndPan(map, point, zoom) {
        map.setZoom(Math.min(10, zoom));
        window.setTimeout(function() {
            map.panTo(point);                
        }, 700)
    }        
    
    function createMap(id, points, markers, options) {
        // create map
        //var map = new GMap2($('#'+id)[0])
        options = options || {}
        var map = new GMap2(document.getElementById(id))
        
        // center
        if(points[options.focus]) {
            var p = points[options.focus]
            map.setCenter(p.point, p.zoom)
        }
        else if(options.focus && options.focus.point) {
            map.setCenter(options.focus.point, options.focus.zoom)
        }
        else {
            // show the whole world
            map.setCenter(new GLatLng(3.513421, 9.140625), 1)
        }
                
        // Add clickable markers
        $.each(markers, function() {
            GEvent.addListener(this, 'click', function() {
                if(this._uri) {
                    document.location.href = this._uri
                }
            })
            map.addOverlay(this)
        })

        // add tooltips to markers
        $('#' + id + ' img').tooltip({ 
            track: true, 
            delay: 0, 
            showURL: false, 
            extraClass: "map",
            fade: 250 
        });
        
        return map
    }    

    
    
    return {
        getIcon: function(type) {
            if(!icons)
                initIcons()
            return icons[type] || icons['default']
        },
        smallMap: function(id, points, markers, options) {
            var map = createMap(id, points, markers, options)
            map.addControl(new GSmallMapControl());
            //map.checkResize()
            // map.updateSize()
            return map
        },
        largeMap: function(id, points, markers, options) {
            var map = createMap(id, points, markers, options)
            
    
            // add controls
            map.addControl(new GSmallMapControl());
            //map.addControl(new GMapTypeControl()); 
            //map.addControl(new GOverviewMapControl());     
            //map.addMapType(G_PHYSICAL_MAP);
    
            // animate zoom
            map.enableContinuousZoom()
            
            return map
        },
        locations: function(id) {
            // Hook up click-events to tree menu
            $('#' + id).find('a.maplink').click(function() {
                var id = $(this).attr('alt')
                if(bounds[id]) {

                    var p = points[id]
                    if(map.getZoom() > points[id].zoom) {
                        zoomAndPan(p.point, p.zoom)
                    }
                    else {
                        panAndZoom(p.point, p.zoom)
                    }

                }
                return false
            })

        }
    }
})()

function apply_reshit(el) {
    var id = $(el).attr('id');
    var favorites = Favorites.get('favorites').add(id);
    if(favorites) {
        favorites.store()
    }
    window.location.href = '/favoriter/?id=' + id + '#' + id;
    return false;        
}

$(function() {    
    
    // ========
    // = Maps =
    // ========
    $(document.body).unload(function() {
        if (GBrowserIsCompatible()) {
            GUnload()
        }
    })
    
    
    // =====================
    // = Tabs and popboxes =
    // =====================
    $('#tabs').tabs()
    $('.image_strip').popbox()
    $('.images').popbox()
    $('.media').popbox()    


    // ===================
    // = Remote validate =
    // ===================
    $('.remotevalidate').remoteValidate()
    
    
    // =============
    // = Ajax form =
    // =============
    // $('.ajaxform').ajaxForm({
    //     beforeSubmit: function(data, $form) {
    //         var s = CKEDITOR.instances['content'].getData()
    //         $.each(data, function() {
    //             if(this.name == 'content') {
    //                 this.value = s
    //             }
    //         })                
    //         $form[0].content.value = s
    //         return $form.data('valid') || false
    //     },
    //     dataType: 'json',            
    //     success: function() {
    //         $.jGrowl('Sparat')
    //     }
    // })
    



    // ==========
    // = Slider =
    // ==========
    /*
    <div class="slidercontainer">
        <table>..</table>
        <div class="slider">
            <div class="handle"></div>    
        </div>
    </div>
    */    
    $('.slidercontainer').each(function() {
        var container = $(this);
        var handle = $('.handle', this)
        var table = $('table', this);
        var val = $.cookie('pos-offers-value')

        var itemsWidth = table.width() - container.width();
        part_out_of_scope = itemsWidth / container.width()
        $('.handle', container).width((1-part_out_of_scope) * container.width())

        var slider = $('.slider', container).slider({  //'.slider', container
            minValue: 0,
            maxValue: itemsWidth,
            handle: handle,
            stop: function (event, ui) {
                var left = ui.value * (ui.value > 0 ? -1 : 1);
                table.animate({'left': left}, 500);
                $.cookie('pos-offers-value', ui.value, {path: '/', expires: 365})
            },
            slide: function (event, ui) {
                var left = ui.value * (ui.value > 0 ? -1 : 1);
                table.css('left', left + 'px');
            }
        }).data('ui-slider').moveTo(parseInt($.cookie('pos-offers-value')) || 0, handle)
    })

    // ============
    // = Sortable =
    // ============
    $("table.sortable").each(function() {
        var sortList = [];
        if(this.id && $.cookie('ts_' + this.id)) {
            var sortList = eval($.cookie('ts_' + this.id))
        }
        $(this).tablesorter({
            sortList: sortList, 
            widgets: ['zebra'],
            textExtraction: function(td) {
                return $(td).attr('pos:value') || td.innerHTML
            }            
        }).bind('sortEnd', function(e) {
            if(e.target.id) {
                var sortList = '[['+e.target.config.sortList[0]+']]';  // [col_num, sort_order 0|1]
                $.cookie('ts_' + e.target.id, sortList, {path: '/'})
            }
        })
    })    

    
    // =============
    // = Favorites =
    // =============
    Favorites = Persistent.extend({
        init: function(name) {
            this._super(name)
            this.items = []
        },
        get: function(id) {
            for(var i in this.items) {
                if(this.items[i].id == id) {
                    return this.items[i]
                }
            }        
            return this.items[id]
        },
        add: function(id, comment) {
            for(var i in this.items) {
                if(this.items[i].id == id) {
                    $.jGrowl('<p>Finns redan i mina favoriter</p><p><a href="/favoriter/" style="color: #65bade">Gå till Favoriter</a></p> ')
                    return false
                }
            }
            this.items.push({id: id, comment: comment || ''})
            $.jGrowl('<p>Tillagd i mina favoriter</p><p><a href="/favoriter/" style="color: #65bade">Gå till Favoriter</a></p> ')
            $('#favorites').html('favoriter (' + this.items.length + ')')
            return this
        },
        remove: function(id) {
            index = null
            for(var i in this.items) {
                if(this.items[i].id == id) {
                    this.items.splice(i, 1)
                    break
                }
            }
            $('#favorites').html('favoriter (' + this.items.length + ')')
            return this
        },
        empty: function() {
            this.items = []
            $('#favorites').html('favoriter')
            return this
        }
    })
    
    $('#favorites').each(function() {
        $(this).html('favoriter (' + Favorites.get('favorites').items.length + ')')
    })
    
    $('.reshit').click(function(e) {
        var a = $(e.target.firstChild).parents('a')[0];
        apply_reshit(a);
    })
    

    

    // ===========
    // = Rotator =
    // ===========
    // $('.rotator').each(function() {
    //     if($(this).hasClass('autohide')) {
    //         $(this).rotator({'autohide': true})
    //     }
    //     else {
    //         $(this).rotator()
    //     }
    // })
    
    // ==========
    // = Banner =
    // ==========
    $('.large_banners').banner()
    
    
    // ===========
    // = Tooltip =
    // ===========
    $('.tooltip').tooltip({ 
        track: true, 
        delay: 0, 
        showURL: false, 
        fade: 250 
    });    
})



function createHeader(lat,lng,zoom) {
    /* 
    - collect all images in header and create slide show
    - add event listeners to buttons in toolbars
    - store btn state in toolbar in cookie
    - 
    */
    var header = $('.headerbox')
    var map_button = header.find('.toolbar .mapbutton')
    var slideshow_button = header.find('.toolbar .slideshowbutton')    
    var map_initialized = false
    function showMap() {
        slideshow_button.removeClass('selected')
        map_button.addClass('selected')
        header.children('.slideshow').hide()
        header.children('.map').show()
        if(!map_initialized) {
            createMap(header.children('.map')[0], lat, lng, zoom)
        }
        return false        
    }
    function showSlideshow() {
        map_button.removeClass('selected')
        slideshow_button.addClass('selected')
        header.children('.map').hide()
        header.children('.slideshow').show()
        return false
    }
    // hook up listeners
    
    $('.mapbutton').click(showMap)
    header.find('.toolbar .slideshowbutton').click(showSlideshow)
    
    // select an item
    if($.cookie('pos_toolbar') == 'map') {
        showMap()
    }
    else {
        showSlideshow()
    }
}


// function createMap(id, points, markers, options) {
//     // create map
//     //var map = new GMap2($('#'+id)[0])
//     options = options || {}
//     var map = new GMap2(document.getElementById(id))
//     
//     // center
//     if(points[options.focus]) {
//         var p = points[options.focus]
//         map.setCenter(p.point, p.zoom)
//     }
//     else if(options.focus && options.focus.point) {
//         map.setCenter(options.focus.point, options.focus.zoom)
//     }
//     else {
//         // show the whole world
//         map.setCenter(new GLatLng(3.513421, 9.140625), 1)
//     }
//             
//     // Add clickable markers
//     $.each(markers, function() {
//         GEvent.addListener(this, 'click', function() {
//             if(this._uri) {
//                 document.location.href = this._uri
//             }
//         })
//         map.addOverlay(this)
//     })
// 
//     // add tooltips to markers
//     $('#' + id + ' img').tooltip({ 
//         track: true, 
//         delay: 0, 
//         showURL: false, 
//         extraClass: "map",
//         fade: 250 
//     });
//     
//     return map
// }    

// var LargeMap = Class.extend({
//     init: function(id, points, markers, conf) {
//         this.points = points
//         this.markers = markers
//         this.map = new GMap2($('#'+id+' .map')[0])        
//         this.container = $('#' + id)
//         this.toolbar = this.container.children('.toolbar')        
//         this._toggle =this.toolbar.find('.toggle a')
//         this.conf = conf || {}
//         var self = this
// 
//         // Add clickable markers
//         var map = this.map
//         $.each(markers, function() {
//             GEvent.addListener(this, 'click', function() {
//                 if(this._uri) {
//                     document.location.href = this._uri
//                 }
//             })
//             map.addOverlay(this)
//         })
//         
//         // add tooltips to markers
//         $('#' + id + ' img').tooltip({ 
//             track: true, 
//             delay: 0, 
//             showURL: false, 
//             extraClass: "map",
//             fade: 250 
//         });
// 
//         // Add controls
//         map.addControl(new GSmallMapControl());
//         map.enableContinuousZoom() // anmiate zooming
// 
//         // Add listeners
//         this._toggle.click(function() {
//             self.toggle()
//             return false
//         })
//         
//         if(this.conf.centerId) {
//             this.centerId(this.conf.centerId)
//         }
//         else {
//             this.centerWorld()
//         }    
//         if($.cookie('LargeMapState') == 'expanded') {
//             this.expand()
//         }
//         
//     },
//     centerWorld: function() {
//         this.map.setCenter(new GLatLng(3.513421, 9.140625), 1)
//     },
//     centerId: function(id) {
//         var p = this.points[id]
//         if(p) {
//             this.centerPoint(p.point, p.zoom)
//         }
//         return this        
//     },
//     centerPoint: function(point, zoom) {
//         this.map.setCenter(point, zoom)
//         return this        
//     },
//     expand: function() {
//         this.container.animate({height: 220})
//         this._toggle.addClass('collapse').html('Dölj karta')    
//         $.cookie('LargeMapState', 'expanded', {expires: 2, path: '/'})
//         return this
//     },
//     collapse: function() {
//         this.container.animate({height: 0})        
//         this._toggle.removeClass('collapse').html('Visa karta')
//         $.cookie('LargeMapState', null, {expires: 2, path: '/'})
//         return this        
//     },
//     toggle: function() {
//         if($.cookie('LargeMapState') == 'expanded') {
//             this.collapse()
//         }
//         else {
//             this.expand()
//         }
//         return this        
//     }
//     
// })


function refresh_maplist(map) {
    // bounds = google bounds object
    if($('#hotels').length) {
        var bounds = map.getBounds()
        var ne = bounds.getNorthEast()
        var sw = bounds.getSouthWest()
        var defaults = {
            url: '/hotel/maplist',
            data: {
                ne_lat: ne.lat(), 
                ne_lng: ne.lng(),
                sw_lat: sw.lat(),
                sw_lng: sw.lng()
            },
            type: 'get',
            error: function(xhr, errType, ex) {
                alert(errType)
            },
            success: function(response) {
                $('#hotels').html(response)
            }
        }
        return $.ajax(defaults)
    }
}





function create_map(args) {
    
    if(!GBrowserIsCompatible()) {
        return true;
    }

    
    // arguments
    var id = args.id || "map"
    var bounds = args.bounds
    var markers = args.markers
    var focusBound = args.focusBound
    var focusId = args.focusId

    // create new map
    var map = new GMap2(document.getElementById(id));
    

    
    // functions
    function centerBound(bound) {
        map.setCenter(bound.getCenter())
        var zoom = map.getBoundsZoomLevel(bound);
        map.setZoom(Math.min(10, zoom));
    }
    

    
    // center
    if(focusId && points[focusId]) {
        var p = points[focusId]
        map.setCenter(p.point, p.zoom)
    }
    else if(focusBound) {
        centerBound(focusBound)
    }
    else {
        // show the whole world
        map.setCenter(new GLatLng(3.513421, 9.140625), 1);
    }

    
    // add controls
    map.addControl(new GLargeMapControl());
    //map.addControl(new GMapTypeControl()); 
    map.addControl(new GOverviewMapControl());     
    //map.addMapType(G_PHYSICAL_MAP);
    
    // animate zoom
    map.enableContinuousZoom()
    

    
    // Add markers
    $.each(markers, function() {
        GEvent.addListener(this, 'click', function() {
            if(this._uri) {
                document.location.href = this._uri
            }
        })
        map.addOverlay(this)
    })
    
    // add event listeners
    // GEvent.addListener(map, 'dragend', function() {
    //     refresh_maplist(map)
    // })
    // GEvent.addListener(map, 'zoomend', function(old_zoom, new_zoom) {
    //     refresh_maplist(map)
    // })


    function panAndZoom(point, zoom) {
        map.panTo(point);           
        window.setTimeout(function() {
            map.setZoom(Math.min(10, zoom));                 
        }, 700)
    }
    function zoomAndPan(point, zoom) {
        map.setZoom(Math.min(10, zoom));
        window.setTimeout(function() {
            map.panTo(point);                
        }, 700)
    }    

    // Hook up click-events to tree menu
    $('#locations').find('a.maplink').click(function() {
        var id = $(this).attr('alt')
        if(bounds[id]) {
            // map.panTo(bounds[id].getCenter())
            // window.setTimeout(function() {
            //     centerBound(bounds[id])
            // }, 700)
            var p = points[id]
            if(map.getZoom() > points[id].zoom) {
                zoomAndPan(p.point, p.zoom)
            }
            else {
                panAndZoom(p.point, p.zoom)
            }

        }
        return false
    })
    
    
    $('#' + id + ' img').tooltip({ 
        track: true, 
        delay: 0, 
        showURL: false, 
        extraClass: "map",
        fade: 250 
    });
    
}





function create_minimap(args) {
    
    if(!GBrowserIsCompatible()) {
        return true;
    }

    
    // arguments
    var id = args.id || "map"
    var bounds = args.bounds
    var markers = args.markers
    var focusBound = args.focusBound
    var focusId = args.focusId

    // create new map
    var map = new GMap2(document.getElementById(id));
    

    
    // functions
    function centerBound(bound) {
        map.setCenter(bound.getCenter())
        var zoom = map.getBoundsZoomLevel(bound);
        map.setZoom(Math.min(10, zoom));
    }
    
    // center
    centerBound(focusBound)
    
    // add controls
    map.addControl(new GSmallMapControl());    

    
    // Add markers
    $.each(markers, function() {
        GEvent.addListener(this, 'click', function() {
            if(this._uri) {
                document.location.href = this._uri
            }
        })
        map.addOverlay(this)
    })


    function panAndZoom(point, zoom) {
        map.panTo(point);           
        window.setTimeout(function() {
            map.setZoom(Math.min(10, zoom));                 
        }, 700)
    }
    function zoomAndPan(point, zoom) {
        map.setZoom(Math.min(10, zoom));
        window.setTimeout(function() {
            map.panTo(point);                
        }, 700)
    }    
    

    // Hook up click-events to tree menu
    $('#locations').find('a.maplink').click(function() {
        var id = $(this).attr('alt')
        if(bounds[id]) {
            // map.panTo(bounds[id].getCenter())
            // window.setTimeout(function() {
            //     centerBound(bounds[id])
            // }, 700)
            var p = points[id]
            if(map.getZoom() > points[id].zoom) {
                zoomAndPan(p.point, p.zoom)
            }
            else {
                panAndZoom(p.point, p.zoom)
            }

        }
        return false
    })
    
    $('#' + id + ' img').tooltip({ 
        track: true, 
        delay: 0, 
        showURL: false, 
        extraClass: "map",
        fade: 250 
    });
}





var map;

function setTooltips() {
    $('.map area[title], #minimap area[title], .map img[title], #minimap img[title], ').tooltip({
        track: true, 
        delay: 0, 
        showURL: false, 
        extraClass: "map",
        fade: 250
    })        
}

function onClusterMarkerClick(args) {
    var tabs = [];
    $.each(args.clusteredMarkers, function(i, marker) {
        if(i == 4) 
            return false;
        var tab = new GInfoWindowTab(i+1, getMarkerContent(marker));
        tabs.push(tab);
    })

    args.clusterMarker.openInfoWindowTabsHtml(tabs, {maxWidth: 350});

}

function addMarkers(map, options) {
    options = options || {}
    var url = options.url || '/map/markers'
    var bounds = map.getBounds()
    var zoom = map.getZoom()
    var ne = bounds.getNorthEast()
    var sw = bounds.getSouthWest()        
    var data = {
        ne_lat: ne.lat(), 
        ne_lng: ne.lng(),
        sw_lat: sw.lat(),
        sw_lng: sw.lng(),
        zoom: zoom
    }
    if(options.clear) {
        data['clear'] = 1
        map.clearOverlays()
    }
    $.getJSON(url, data, function(data, textStatus) {
        $.each(data.markers, function(i) {
            var m = new GMarker(new GLatLng(this.lat, this.lng), {title: this.title})
            var self = this       
            GEvent.addListener(m, 'click', function() {
                window.location.href = self.uri
            })
            map.addOverlay(m)
        })
        if(data.markers.length) {
            setTooltips()
        }
    })
}

function createMap(el, lat, lng, zoom, url) {
    if(!el) {
        return;
    }
    map = new GMap2(el)
    map.setUIToDefault();    
    map.setMapType(G_PHYSICAL_MAP);
    map.disableScrollWheelZoom();
    map.setCenter(new GLatLng(lat, lng), parseInt(zoom))

    setTooltips()

    GEvent.addListener(map, 'moveend', function() {
        addMarkers(map, {url: url})
    })
    GEvent.addListener(map, 'zoomend', function(oldlvl, newlvl) {
        // setTooltips()
        addMarkers(map, {clear: true, url: url})
    })        
    
    addMarkers(map, {clear: true, url: url})    
}
