$(document).ready(function(){
    
    // AIzaSyDwf713uX3juf_I6snDrhgYHQlHNM-s8-4
    
    function Projects_map(options) {

        var that = this, // Scope, lyk
        options = options || {}; // Get options array

        // Function to render map to page
        this.render_map = function() {

            // JSON for map styling
            var map_style = new google.maps.StyledMapType([{
                featureType: "administrative.country",
                elementType: "labels",
                stylers: [{ visibility: "off" }]
            }, {
                featureType: "administrative.locality",
                elementType: "all",
                stylers: [{ visibility: "off" }]
            }, {
                featureType: "poi",
                elementType: "all",
                stylers: [{ visibility: "off" }]
            }, {
                featureType: "road",
                elementType: "all",
                stylers: [{ visibility: "off" }]
            }, {
                featureType: "transit",
                elementType: "all",
                stylers: [{ visibility: "off" }]
            }, {
                featureType: "water",
                elementType: "labels",
                stylers: [{ visibility: "off" }]
            }, {
                featureType: "landscape",
                elementType: "all",
                stylers: [{ visibility: "off"}]
            }, {
                featureType: "water",
                elementType: "geometry",
                stylers: [
                    { hue: "#e8f1f7" },
                    { saturation: 10 },
                    { lightness: 40 },
                    { gamma: 0},
                    { visibility: "on" }
                ]
            }], {name: "Plain"});

            // Instantiate Google maps object
            that.map = new google.maps.Map(document.getElementById(options.element), {
                backgroundColor: "#f5f8fb",
                disableDefaultUI: true, // Disable default UI
                zoom: 5, // Zoom to level one
                center: new google.maps.LatLng(34.297855, -99.740372), // Centre on US
                mapTypeId: "Plain", // Map type to road
                draggable: false, // Disable dragging
                disableDoubleClickZoom: true, // Disable zooming
                scrollwheel: false // Disable zooming
            });

            // Set map type to plain
            that.map.mapTypes.set("Plain", map_style);

        };

        // Returns JSON for projects 
        this.get_projects = function() {

            var projects; // Variable to store projects

            $.ajax({
                url: options.json,
                dataType: "json",
                async: false,
                success: function(data) {
                    projects = data; // Assign JSON
                }
            });

            return projects; // Return JSON

        };

        this.render_projects = function() {

            populate_tooltip = function(project, event) {

                // Hide tooltip incase it's already open
                tooltip.hide();

                 // Find inner div and clear its contents
                tooltip.inner = tooltip.find("div");
                tooltip.inner.html("");

                // Set tooltip contents
                tooltip.inner.append("<h1>" + project.name + "</h1>");
                tooltip.inner.append("<p class=\"desc\">" + project.desc + "<a href=\"" + project.project_url + "\">View them now</a>.</p>");
                tooltip.inner.append("<p class=\"tools\"><a class=\"close\">Close</a> <a href=\"" + project.project_url + "\" class=\"button\">View jobs in this town &raquo;</a></p>");

                // Event listener for tooltip close button
                tooltip.inner.find("a.close").bind('click', function() {
                    tooltip.hide();
                    tooltip.inner.html("");
                    // Loop through all markers and unset them
                    $.each(projects, function(index, value) {                    
                        this.setIcon(options.inactive_marker);
                        this.is_active = false;
                    });
                });

                // Set position of tooltip
                // Note: math here is because tooltip is set in the container above the Google map
                tooltip.css("top", event.pixel.y - (tooltip.outerHeight() / 2) + 10);

                // Check if there's enough space to render to the right - if not, render left
                if (($("div#projects_map").outerWidth() - event.pixel.x) < 280) {

                    tooltip.css("left", event.pixel.x - 195);
                    tooltip.addClass("right");


                } else {
                    tooltip.removeClass("right");
                    tooltip.css("left", event.pixel.x + 90);


                }

                // Show tooltip
                tooltip.fadeIn("fast");

            };

            // Get projects from JSON
            var json = that.get_projects(),
            projects = {},
            tooltip = $("div#map_tooltip");

            // Hide tooltip
            tooltip.hide();

            // Loop through each project, render to map
            $.each(json, function(i, project) { 

                // Create marker
                projects[i] = new google.maps.Marker({
                    position: new google.maps.LatLng(project.lat, project.lng), 
                    map: that.map,
                    icon: options.inactive_marker,
                    cursor: "pointer",
                    optimized: false
                }); 

                // Event listener for mouseover
                google.maps.event.addListener(projects[i], 'mouseover', function() {
                    this.setIcon(options.active_marker);
                });

                // Event listener for mouseout
                google.maps.event.addListener(projects[i], 'mouseout', function() {
                    if (!this.is_active) {
                        this.setIcon(options.inactive_marker);
                    }
                });

                // Event listener for tooltip
                google.maps.event.addListener(projects[i], 'click', function(event) {

                    this.setIcon(options.active_marker);
                    this.is_active = true;

                    // Loop through all except this marker and unset them
                    $.each(projects, function(index, value) {
                        if (value !== projects[i]) {
                            this.setIcon(options.inactive_marker);
                        }
                    });

                    // Launch tooltip onclick
                    populate_tooltip(project, event);

                });

            });

            // Mouse events for tooltip
            $(document).mouseup(function(e) {

                // Don't close if we're on the map tooltip
                $("div#map_tooltip div").mouseup(function() {
                    return false;
                });

                // Close if we click on something that's not a marker
                $("div#map_tooltip").hide();

                // Unset all markers
                $.each(projects, function(index, value) {
                    this.setIcon(options.inactive_marker);
                });

            });

        };

        this.render_map();
        this.render_projects();

    }
    
    // Check if the map is on the page.
    if ($("div#projects_map").length) {
        var projects_map = new Projects_map({
            element: "map_interface",
            json: "/jobs/projects_map_json"
        });   
    }
    
    quick_jump();
    
});

function quick_jump() {
    $('select.quick_jump').bind('change', function() {
        window.location = $(this).val();
    });
}

