var map;
var distIcon = new GIcon();
var currentView;
var request_url;
var request_params;

distIcon.image = Stratos.makeUrl('./views/images/white_marker.png');
distIcon.iconSize = new GSize(20, 34);
distIcon.iconAnchor = new GPoint(6, 6);
distIcon.infoWindowAnchor = new GPoint(6,6);

function load() {
    currentView = $("#view").val();

    if( currentView == 'map' )
    {
        //  Set the mapelement
        map = new GMap2(document.getElementById("map"));
        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
    
        map.addControl(new GSmallMapControl(), topRight);
    
        map.addMapType(custommap);
        map.addMapType(geologymap);
    
        map.setCenter(new GLatLng(30.000000, -98.000000), 8, geologymap);
    }
     
    
    updateMap();	
} 

function selectTaxaItem(li) {
    
    $("#scientific_type").val(li.extra[0]);
    //$("#site_id").val('');
    //$("#project_id").val('');

    
    updateMap();
}

function updateMap() {
    
    currentView = $("#view").val();
    
    var scientific_name = $("#taxa_lookup").val();
    var scientific_type = $("#scientific_type").val();
    var common_name = $("#common_name").val();
    var level2 = $("#level2").val();
    var level3 = $("#level3").val();
    var level4 = $("#level4").val();
    var strat_group = $("#strat_group").val();
    var strat_formation = $("#strat_formation").val();
    var strat_member = $("#strat_member").val();
    var collector = $("#collector").val();
    var collection = $("#collection").val();
    var specimen_number = $("#specimen_number").val();
    var suffix = $("#suffix").val();
    var era = $("#era").val();
    var use_era = $("#use_era").attr('checked');
    var period = $("#period").val();
    var use_period = $("#use_period").attr('checked');
    var epoch = $("#epoch").val();
    var use_epoch = $("#use_epoch").attr('checked');
    var age = $("#age").val();
    var use_age = $("#use_age").attr('checked');
    var page = $("#page").val();
    var page_size = $("#page_size").val();
    
    if (scientific_name == 'type a scientific name')
    {
        scientific_name = '';   
    }
    
    if( specimen_number == 'Specimen Number' )
    {
        specimen_number = '';   
    }
    
    if( suffix == 'Suffix' )
    {
        suffix = '';   
    }
    
    request_params = {  taxa:scientific_name, 
                        scientific_type:scientific_type,
                        common_name:common_name,
                        level2:level2, 
                        level3:level3, 
                        level4:level4, 
                        strat_group:strat_group, 
                        strat_formation:strat_formation, 
                        strat_member:strat_member,
                        collection:collection,
                        collector:collector,
                        specimen_number:specimen_number,
                        suffix:suffix,
                        era:era,
                        use_era:use_era,
                        period:period,
                        use_period:use_period,
                        epoch:epoch,
                        use_epoch:use_epoch,
                        age:age,
                        use_age:use_age,
                        page:page,
                        page_size:page_size };
                          
    request_params['format'] = 'json';
    
    request_url = Stratos.makeUrl('Map/getSpecimens', request_params);
    
    var bookmark_params = {};
    
    $.each(request_params, function(key, val) {
        if( val != '' )
        {
            bookmark_params[key] = val;
        }
    });
    
    var bookmark_url = Stratos.makeUrl('Map', bookmark_params);
    
    if( currentView == 'map' )
    {
        showDiv('loading');

        $("#extra > #overlays").show();
        $("#extra > #paging").hide();
        
        map.clearOverlays();
        mapUtil.minLat = null;
        mapUtil.maxLat = null;
        mapUtil.minLng = null;
        mapUtil.maxLng = null;
    
        $("#record_pane").html('');
        $("#record_count").html('');
        
        $.getJSON(request_url,
            function(data){
    
                var total = data[0][0];
                var offset = data[0][1];
                var page_size = data[0][2];
                var max_page = data[0][3];
                var prev_url = '';
                var next_url = '';
            
                // $("#paging").html('');
                             
                var page = parseInt($("#page").val());
    
                if( max_page > 1 ) 
                {                     
                    if( page > 1 )
                    {
                        $("#record_count").append('<a id="prev">&laquo; prev</a> ')
                    }
                   
                    
                    $("#record_count").append(parseInt(offset+1) + ' - ' + Math.min(parseInt(offset+page_size), total) + ' of ' + total + ' records ');
                    
                    if( page < max_page )
                    {
                        $("#record_count").append('<a id="next">next &raquo;</a>');
                    }
                    
                    $("#record_count").append('</div>');
                    
                    $("#prev").click(function() { $("#page").val(page-1); updateMap(); });
                    $("#next").click(function() { $("#page").val(page+1); updateMap(); });
    
                }
                
                var specimens = data[1];
         
                if( specimens.length == 0 )
                {
                    $("#record_pane").append('<div id="record_count">No Records Found</div>');
                }
                
                $.each(specimens, function(i,item){
                           
                    $('#record_pane').append('<div id="' + item.specimen_id + '" class="record_small"><div class="record_number">' + item.specimen_number + '</div><div>' 
                                               + item.scientific_name + '</div><div>' + item.geography_display + '</div><a class="record_link" href="' + Stratos.makeUrl('Collection/get', {id:item.specimen_id}) + '">Record Details</a></div>');
                    
                    if( item.latitude != '0.0000' && item.longitude != '0.0000' )
                    {
                        
                        mapUtil.calculateBorders(item.latitude, item.longitude);
                        
                        var point = new GLatLng(item.latitude, item.longitude);
                           
                        var info_window = '';
                        
                        var info_window = '<h3>' + item.scientific_name + '</h3>' + item.specimen_number + '<br />' + item.geography_display + '<br />' + item.latitude + '&deg;, ' + item.longitude + '&deg; ';
                
                        var distMarker = new GMarker(point,distIcon);
        
                       GEvent.addListener(distMarker, "click", function() {
                            //distHtml = '<img style="width: 160px; height: 120px;" src="'+ imgUrl + '" /><br /><br />' + first_name + ' ' + last_name + '<br />' + location_display + '<br />' + latitude + '&deg; ' + longitude + '&deg; ' + '<br />' + date_of_record + '<br /><br /><a target="_blank" href="' + Stratos.makeUrl('Photo/get', {specimen_id:specimen_id}) + '">View Record Details</a>';
                    
                            distMarker.openInfoWindowHtml(info_window);
                        });
            
                        map.addOverlay(distMarker);
        
                        $('#' + item.specimen_id).click(function() {
                           map.panTo(new GLatLng(item.latitude, item.longitude));
                           distMarker.openInfoWindowHtml(info_window);
                        });
                    
                    }
                    
                });
                
                mapUtil.zoomToViewAll();
    
                $(".map_button").fadeIn('slow');
                
                hideDiv('loading');
        });
    }
    else
    {
        $("#extra > #overlays").hide();
        $("#extra > #paging").show();
        
        $.getJSON(request_url,
            function(data){
    
                var total = data[0][0];
                var offset = data[0][1];
                var page_size = data[0][2];
                var max_page = data[0][3];
                var prev_url = '';
                var next_url = '';
            
                // $("#paging").html('');
                             
                var page = parseInt($("#page").val());
    
                $("#extra > #paging").html('');

                if( max_page > 1 ) 
                { 
                    $("#extra > #paging").append('<div id="record_count"></div>');
                    
                    if( page > 1 )
                    {
                        $("#record_count").append('<a id="prev">&laquo; prev</a> ')
                    }
                   
                    $("#record_count").append(parseInt(offset+1) + ' - ' + Math.min(parseInt(offset+page_size), total) + ' of ' + total + ' records ');
                    
                    if( page < max_page )
                    {
                        $("#record_count").append('<a id="next">next &raquo;</a>');
                    }
                    
                    $("#record_count").append('</div>');
                    
                    $("#prev").click(function() { $("#page").val(page-1); updateMap(); });
                    $("#next").click(function() { $("#page").val(page+1); updateMap(); });
    
                }
                
                var specimens = data[1];
                 $("#table_view_records").html('');
                $("#table_view_records").append('<table id="record_table"><tr><th>Record</th><th>Scientific Name</th><th>Geography</th></table>');
                
                if( specimens.length == 0 )
                {
                    $("#record_table").append('<tr><td colspan="3" align="center">No Records Found</td></tr>');
                }
                
                $.each(specimens, function(i,item){
                           
                    $('#record_table').append('<tr id="' + item.specimen_id + '"><td><a class="record_link" href="' + Stratos.makeUrl('Collection/get', {id:item.specimen_id, back_to:'table'}) + '">' + item.specimen_number + '</a></td><td>' 
                                               + item.scientific_name + '</td><td>' + item.geography_display + '</td></tr>');
                    
                });
                                
                $("#record_table tr:even").addClass("even");
                
                $("#record_table tr").bind( "mouseover", function(e){
                   $(this).toggleClass("highlight");
                });
                
                $("#record_table tr").bind( "mouseout", function(e){
                   $(this).toggleClass("highlight");
                });

                $("#record_table tr").click(function() { 
                    window.location = Stratos.makeUrl('Collection/get', {id:$(this).attr('id'), back_to:'table'})
                });
                
                $(".map_button").fadeIn('slow');
                
        });
    }
}

function formatItem(row) {
    return row[0].substr(0, 1).toUpperCase() + row[0].substr(1);
}


//  Show a div
function showDiv(id) {
  var element = document.getElementById(id);
  element.style.visibility = 'visible';
}

//  Hide a div
function hideDiv(id) {
  var element = document.getElementById(id);
  element.style.visibility = 'hidden';
}

function createMarker(specimen_id, point, latitude, longitude, geography_display, scientific_name, specimen_number, info_window) {
    //var imgUrl = Stratos.makeUrl('Photo/displayPhoto', {specimen_id:specimen_id});
    
    GEvent.addListener(distMarker, "click", function() {
        //distHtml = '<img style="width: 160px; height: 120px;" src="'+ imgUrl + '" /><br /><br />' + first_name + ' ' + last_name + '<br />' + location_display + '<br />' + latitude + '&deg; ' + longitude + '&deg; ' + '<br />' + date_of_record + '<br /><br /><a target="_blank" href="' + Stratos.makeUrl('Photo/get', {specimen_id:specimen_id}) + '">View Record Details</a>';
        distMarker.openInfoWindowHtml(info_window);
    });
    
    return distMarker;
}

$(document).ready(function() {
    

    $("#taxa_lookup").autocomplete(
    Stratos.makeUrl('Taxa/search'), {
        delay:200,
        minChars:3,
        matchSubset:1,
        matchContains:1,
        cacheLength:10,
        onItemSelect:selectTaxaItem,
        formatItem:formatItem,
        autoFill:true
    });
    
    $(".clear_click").click(function() {
        $(this).val('');
        $(this).css('color', 'black');
    });
    
    $("#common_name").change(
        function()
        {
            $('#taxa_lookup').val('type a scientific name');
        }
    );
    
    $('#level2').change(
        function() { 
            if( $(this).val() == 'USA' )
            {
                $('#level3').attr('disabled', false); 
                $('#level3').children().remove();
                $('#level3').append('<option value="">- Any State - </option>');

                $.each(stratos.response['result']['usa_states'], function(i, item) { 
                    $("<option>").attr("value", item).text(item).appendTo("#level3"); 
                });
                
            }
            else if( $(this).val() == 'Mexico' )
            {
                $('#level3').attr('disabled', false); 
                $('#level3').children().remove();
                $('#level3').append('<option value="">- Any State - </option>');

                $.each(stratos.response['result']['mexico_states'], function(i, item) { 
                    $("<option>").attr("value", item).text(item).appendTo("#level3"); 
                });
            }
            else
            {
                $('#level3').attr('disabled', true); 
                $('#level4').attr('disabled', true); 
            }
        }
    );
    
    $('#level3').change(  
        function() {
            var selected_state = $("#level3").val();
            
            if( selected_state != '' && $("#level2").val() == 'USA' )
            {
                $.each(stratos.response['result']['counties'][selected_state], function(i, item) { 
                    $("<option>").attr("value", item).text(item).appendTo("#level4"); 
                });
                
                $('#level4').attr('disabled', false); 
            }
        }
    );
    
    $('.map_updater').change(
        function() {
            // if any of the filters changed, start over at page 1 and update the map
            $("#page").val(1);
            updateMap();
        }
    );
    
    $("#toggle_advanced").click(function() { 
        $("#filters_advanced").toggle("slow");
    });
    
    $("#kml_button").click(function() {
        request_params['format'] = 'kml';
        window.open(Stratos.makeUrl('Map/getSpecimens', request_params));
    });
    
    $("#csv_button").click(function() { 
        var scientific_name = $("#taxa_lookup").val();
        
        window.open(Stratos.makeUrl('Map/getSpecimens', {format:'csv'}));
    });
    
    $('.legend_info').tooltip({
        delay: 0, 
        showURL: false, 
        bodyHandler: function() { 
            return $(this).children("label").attr("title"); 
        } 
    });
    
    $('.legend_info').mouseover(function() { $(this).css('background', 'lightblue'); });
    $('.legend_info').mouseout(function() { $(this).css('background', '#eee'); });

    $('.record_small').live('mouseover',
        function() { $(this).addClass('record_small_hover') }
    );
    
    $('.record_small').live('mouseout',
        function() { $(this).removeClass('record_small_hover') }
    );
    
    $(".map_type").click(
        function() {
            if( $(this).val() == 'Geology' )
            {
                $("#geology_legend").show('slow');
   
            }
            else
            {
                $("#geology_legend").hide('slow');   
            }
            switch($(this).val())
            {
                case 'Geology':
                    map.setMapType(geologymap);
                    break;
                case 'County':
                    map.setMapType(custommap);
                    break;
                case 'Terrain':
                    map.setMapType(G_PHYSICAL_MAP);
                    break;
                case 'Satellite':
                    map.setMapType(G_SATELLITE_MAP);
                    break;
                case 'Roads':
                    map.setMapType(G_NORMAL_MAP);
                    break;
                case 'Hybrid':
                    map.setMapType(G_HYBRID_MAP);
                    break;
                default:
                    map.setMapType(custommap); 
            }

        }
    );     
    
    $("#time_slider").slider({
        value:100,
        animate: true,
        min: 0,
        max: 540,
        step: 1,
        slide: function(event, ui) {
            $("#amount").val(ui.value);
            
            var geo_time_period = getGeologicTime(ui.value);
            
            $("#era_filter").html(geo_time_period.era);
            $("#period_filter").html(geo_time_period.period);
            $("#epoch_filter").html(geo_time_period.epoch);
            $("#age_filter").html(geo_time_period.age);
            
            $("#era").val(geo_time_period.era);
            $("#period").val(geo_time_period.period);
            $("#epoch").val(geo_time_period.epoch);
            $("#age").val(geo_time_period.age);
            
        },
        
        stop: function (event, ui) {
            updateMap();
   
        }
        
    });
    
    $("#amount").val($("#time_slider").slider("value"));
    
    $("#toggle_advanced").click(function() { 
        $("#advanced_search").toggle("slow");
    });
    
    $("#toggle_table_view").click(function() { 
        $("#view").val('table');
        $("#map_view").hide(); 
        $("#table_view").show(); 
        updateMap();
    });
    
    $("#toggle_map_view").click(function() {
        $("#view").val('map');
        $("#table_view").hide(); 
        $("#map_view").show();
        updateMap();
    });
    
    load();
});

