var Map = {
    // The Google Map element
    ob: null,
    // The element containing the map
    element: 'map',

    // The container used for resizing the map
    container: 'container',
    
    cluster: null,
    markers: [],
    
    hasMap: false,

    // -- Functions --
    init: function() {
        Map.google_init();
        
        // Load the map if needed
        if(fill_map) {
            Map.load_data(map_filter, true);
        }
    },
    google_init: function() {
        // Set the map center point
        Map.latlng = new GLatLng(51.5, -0.2);
        // Set the Google Map Type Id
        //Map.google_options.mapTypeId = google.maps.MapTypeId.ROADMAP;
    
        // Resize the map div accoring to the comainter size
        Map.checkResize();
        Map.hasMap = jQuery('#'+Map.element).length;
        if(GBrowserIsCompatible() && Map.hasMap) {
            Map.ob = new GMap2(document.getElementById(Map.element));
            map = Map.ob;
            //===== Restrict Zoom Levels =====
            var mapTypes = Map.ob.getMapTypes();
            
            // Overwrite the getMinimumResolution() and getMaximumResolution() methods
            for (var i=0; i<mapTypes.length; i++) {
                mapTypes[i].getMinimumResolution = function() {
                    return 3;
                }
                mapTypes[i].getMaximumResolution = function() {
                    return 11;
                }
            }
            
            // Set the map center
            Map.ob.setCenter(Map.latlng, 4);
            
            // Add the control
            Map.ob.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20,60)));
            
            GEvent.addListener(Map.ob, "zoomend", function() {
                Map.location.save();
            });
            GEvent.addListener(Map.ob, "moveend", function() {
                Map.location.save();
            });
            GEvent.addListener(Map.ob, "dragend", function() {
                Map.location.save();
            });
            // Load the last location from the cookie
            Map.location.load();
        
            // Bind the resize event to the map
            jQuery(window).bind('resize', Map.checkResize);
        }
        
    },
    checkResize: function() {
        // Resize the map's element according to the container width
        if(Map.container != null) {
            jQuery('#'+Map.element).height(jQuery('#content').height());
            
            
            jQuery('#'+Map.element).width('100%');
            //jQuery('#'+Map.element).width(jQuery('#'+Map.container).width());
        }
    
        // Resize the map if it exists
        if(Map.ob != null) {
            Map.ob.checkResize();
        }                
    },
    load_markers: function(uploads, fitzoom) {
        if(Map.hasMap) {
            Map.ob.closeExtInfoWindow();
        
            if(Map.cluster) {
                Map.cluster.clearMarkers();
            }
        
            Map.ob.setCenter(Map.ob.getCenter());
        
            // For the fit zoom
            var bounds = new GLatLngBounds();
        
            var markers = [];
            var markers_ids = [];
            var styles = [];
            for (var key in uploads) {
                var upload = uploads[key];
            
                // Get the upload icon
                var icon = new GIcon();
                icon.shadow = '';
                icon.iconSize = new GSize(64, 60);
                icon.iconAnchor = new GPoint(13, 60);
                icon.image = upload.data.balloon;
            
                //var latlng = new GLatLng(uploads[i].latitude, uploads[i].longitude);
                var latlng = new GLatLng(upload['location']['latitude']*1, upload['location']['longitude']*1);
                var marker = new GMarker(latlng, {icon: icon});
                marker.value = upload;
            
                // Extend the map bounds
                bounds.extend(latlng);
            
                /*
                $(window).bind('upload-'+upload.id, {marker: marker}, function(event) {
                    var marker = event.data.marker;
                    Map.ob.panTo(marker.getPoint());
                    Map.ob.openExtInfoWindow(
                        marker.getLatLng(),
                        "simple_example_window",
                        '<div class="popup img-popup">Loading ...</div>',
                        {
                            ajaxUrl: '/map/video/'+marker.value.id
                        }
                    );
                });
                */
            
                GEvent.addListener(marker, "click", function(ll) {
                    Map.ob.panTo(this.getPoint());
                    /*Map.ob.openExtInfoWindow(
                        this.getLatLng(),
                        "simple_example_window",
                        '<div class="popup img-popup">Loading ...</div>',
                        {
                            ajaxUrl: '/map/video/'+this.value.id
                        }
                    );*/
                    Map.openUpload(this.value.id);
                });
            
                markers.push(marker);
                markers_ids[marker.id] = marker;
            
                // Cluster style
                styles.push({
                    url: "/images/balloon-comments.png",
                    height: 64,
                    width: 68,
                    opt_anchor: [16, 0],
                    opt_textColor: '#FFF'
                });
            }
            Map.markers = markers;
            Map.cluster = new MarkerClusterer(Map.ob, markers, {'zoomOnClick': false, styles: styles});
        
            GEvent.addListener(Map.cluster, "clusterclick", function(cluster) {
                //
                var cdiv = document.createElement('div');
                var cmarkers = cluster.getMarkers();
                // sort newest first
                cmarkers.sort(sortmarkers);
                //Map.ob.setCenter(cmarkers[0].getLatLng());
                var str = '';
                var counter  = 0;
                var current_page = 1;
                var total_pages = Math.ceil(cmarkers.length/8);
                ClusterPagination.total = total_pages;
                ClusterPagination.current_page = 1;
                str += '<div class="popup video-popup cluster-popup">';
                str += '<h3>Cluster</h3>';
                for (var i = 0; i < cmarkers.length; ++i) {
                    if(counter == 0) {
                        if(current_page != 1) {
                            var hide_page = ' style="display: none;"'
                        }
                        else {
                            var hide_page = '';
                        }
                        str += '<ul class="videolist clearfix page'+current_page+'"'+hide_page+'>';
                        current_page++;
                    }
                    counter++;
                    
                    classname = 'img-box';
                    if(cmarkers[i].marker.value.type == 'text') {
                        classname = 'text-box';
                    }
                    //str += '<li class="clearfix">'+cmarkers[i].marker.value.title;
                    str += '<li class="clearfix">';
                    str += '    <div class="'+classname+'" onclick="return Map.openUpload(\''+cmarkers[i].marker.value.id+'\', ['+cmarkers[i].marker.value.location.latitude+', '+cmarkers[i].marker.value.location.longitude+']);">';
                
                    if(cmarkers[i].marker.value.type == 'text') {
                        str += '        <p>'+cmarkers[i].marker.value.description+'</p>';
                    }
                    else {
                        str += '        <img src="'+cmarkers[i].marker.value.data.thumbnail+'" width="105" height="75" />';
                        if(cmarkers[i].marker.value.content_time) {
                            str += '        <div class="timer">'+cmarkers[i].marker.value.content_time+'</div>';
                        }
                    }
                    str += '        <div class="userpopup hideme">';
                    str += '            <div class="clearfix">'+cmarkers[i].marker.value.title+'<br />';
                    str += '                <ul class="clearfix">';
                    str += '                    <li>By <a href="/profile/someone">Becca</a> 3 days ago</li>';
                    str += '                    <li><a href="#">1 comment</a></li>';
                    str += '                </ul>';
                    str += '            </div>';
                    str += '        </div>';
                    str += '    </div>';
                    str += '</li>';
                
                    if(counter == 8 || i==(cmarkers.length-1)) {
                        str += '</ul>';
                        counter=0;
                    }
                };
            
                // Don't show the pagination if there's only one page
                if(total_pages > 1) {
                    str += '<div class="pagination">';
                    str += '    <form action="" method="post" accept-charset="utf-8" onsubmit="return ClusterPagination.open($(\'#pagination_video_cluster input\').val()));">';
                    str += '        <ul id="pagination_video_cluster">';
                    str += '            <li><a href="#" class="first inactive" onclick="return ClusterPagination.open(1);">First</a></li>';
                    str += '            <li><a href="#" class="previous inactive" onclick="return ClusterPagination.previous();">Previous</a></li>';
                    str += '            <li><input value="1" onchange="ClusterPagination.open(this.value);" type="text"> of '+total_pages+' </li>';
                    str += '            <li><a href="#" class="next" onclick="return ClusterPagination.next();">Next</a></li>';
                    str += '            <li><a href="#" class="last" onclick="return ClusterPagination.open('+total_pages+');">Last</a></li>';
                    str += '        </ul>';
                    str += '    </form>';
                    str += '</div>';
                }
                str += '</div>';
                cdiv.innerHTML = str;
                Map.ob.openExtInfoWindow(cluster.getCenter(),"simple_example_window", $(cdiv).html());
                //Map.ob.panTo(Map.ob.ExtInfoWindowInstance_.marker_.getPoint());
            });
        
            /*GEvent.addListener(Map.ob, 'extinfowindowupdate', function() {
                Map.ob.panTo(this.ExtInfoWindowInstance_.marker_.getPoint());
            });*/
            
            if(fitzoom == true && uploads.length != 0) {
                Map.ob.setZoom(Map.ob.getBoundsZoomLevel(bounds));
                Map.ob.setCenter(bounds.getCenter());
            }
        
            GEvent.addListener(Map.ob, 'zoomend', function() {
                Map.ob.closeExtInfoWindow();
            });
            
        }
    },
    searchMap: function(element) {
        if(Map.hasMap) {
            var term = jQuery(element).val();
            
            // Create new geocoding object
            geocoder = new GClientGeocoder();

            // Retrieve location information, pass it to addToMap()
            geocoder.getLocations(term,  function(response) {
                // Retrieve the object
                place = response.Placemark[0];

                // Retrieve the latitude and longitude
                point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                
                // uncomment to reset the map to showing all uploads
                Map.load_data(base_filter, false);
                // Center the map on this point
                Map.ob.setCenter(point, 13);
            });
        }
        
        return false;
    },
    openUpload: function(id, coordinates) {
        
        $('#simple_example_window').hide();
    
        try {
            if(coordinates && Map.hasMap) {
                point = new GLatLng(coordinates[0], coordinates[1]);
                Map.ob.setCenter(point);

                Map.ob.closeExtInfoWindow();
            }
        }
        catch(e) {};
    
        Popup.upload_popup(id);
        
        return false;
    },
    load_data: function(filter, fitzoom) {
        var map_link = '/elements/uploadsmap/'+buster+'.json';
        if(filter) {
            map_link += '?'+filter;
        }
        if(!fitzoom) {
            fitzoom  = false;
        }
        $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
        $.getJSON(map_link, function(data) {
            Map.load_markers(data, fitzoom);
        });
    },
    location: {
        save: function() {
            var mapzoom = Map.ob.getZoom();
            var mapcenter = Map.ob.getCenter();
            var maplat = mapcenter.lat();
            var maplng = mapcenter.lng();
            var cookiestring = maplat + "_" + maplng + "_" + mapzoom;
            var exp = new Date();
            
            //set new date object
            exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
            //set it 30 days ahead
            Map.location.setCookie("tagmap_map_location", cookiestring, exp);
        },
        load: function() {
            var loadedstring = Map.location.getCookie("tagmap_map_location");
            if(loadedstring != "") {
                var splitstr = loadedstring.split("_");
                map.setCenter(new GLatLng(parseFloat(splitstr[0]), parseFloat(splitstr[1])), parseFloat(splitstr[2]));
            }
        },
        setCookie: function(name, value, expires) {
            document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
        },
        getCookie: function(c_name) {
            if (document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=");
                
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    c_end = document.cookie.indexOf(";", c_start);
                    
                    if (c_end == -1)
                        c_end=document.cookie.length;
                        
                    return unescape(document.cookie.substring(c_start,c_end));
                }
            }
            
            return "";
        }
    }
};

function sortmarkers(m1, m2) {
    if(m1.marker.value.creation_timestamp<m2.marker.value.creation_timestamp) {
        return +1;
    }
    else if(m1.marker.value.creation_timestamp == m2.marker.value.creation_timestamp) {
        if(m1.marker.value.id > m2.marker.value.id) {
            return +1;
        }
        else {
            return -1;
        }
    }
    else {
        return -1;
    }
}

var ClusterPagination = {
    current_page: 1,
    total: 0,
    previous: function() {
        if(ClusterPagination.current_page > 1) {
            ClusterPagination.open(ClusterPagination.current_page-1);
        }
        return false;
    },
    next: function() {
        if(ClusterPagination.current_page < ClusterPagination.total) {
            ClusterPagination.open(ClusterPagination.current_page+1);
        }
        return false;
    },
    open: function(page) {
        if(page > ClusterPagination.total) {
            page = ClusterPagination.total;
        }
        else if(page < 1) {
            page = 1;
        }

        ClusterPagination.current_page = page;
        $('.popup .videolist').hide();
        $('.popup .videolist.page'+page).show();
        $('#pagination_video_cluster input').val(page);
        if(ClusterPagination.current_page == 1) {
            $('#pagination_video_cluster .first').addClass('inactive');
            $('#pagination_video_cluster .previous').addClass('inactive');
        }
        else {
            $('#pagination_video_cluster .first').removeClass('inactive');
            $('#pagination_video_cluster .previous').removeClass('inactive');
        }
        if(ClusterPagination.current_page == ClusterPagination.total) {
            $('#pagination_video_cluster .last').addClass('inactive');
            $('#pagination_video_cluster .next').addClass('inactive');
        }
        else {
            $('#pagination_video_cluster .last').removeClass('inactive');
            $('#pagination_video_cluster .next').removeClass('inactive');
        }
        return false;
    }
};
var map;
