// base_url wird in htmlhead.php gesetzt und enthält (überraschung!) die Page URL
// the markers data
var airbases = [];
var searchmarkers = [];
var map = null;
var mapstatus = { 
        "view" : {
        "zoom" : 8,
        "lat" : 47,
        "lng" : 8
    },
    "cc" : null,
    "aid" : null,
    "gid" : null,
    "oid" : null
};


var currentMarker = null;
var clickedX = 0;
var clickedY = 0;
var view = null;

$(document).ready( function() {

    //load preset values
    mapstatus.cc = pre.cc;
    mapstatus.aid = pre.aid;
    mapstatus.oid = pre.oid;
    mapstatus.gid = pre.gid;
    mapstatus.view.zoom = pre.zoom;
    

    /****************************************************
     * Automatic "onLoad" Part
     ***************************************************/

    // Load Marker Coordinates from json controller and initialize the GMap2
    $.post(base_url + 'ajax/markers', {'cc' : mapstatus.cc, 'gid': mapstatus.gid, 'oid': mapstatus.oid, 'allmarkers': true}, function(data) {
        airbases = data.markers;
        mapstatus.view = data.view;
        //FIXME Safari mag die zuweisung von data.view nach status.view nicht. Danach ist status.view undefined !!!!
        
        var center = new google.maps.LatLng(mapstatus.view.lat, mapstatus.view.lng);
        var mapOptions = {
                'zoom' : mapstatus.view.zoom,
                'center' : center,
                'mapTypeId' : google.maps.MapTypeId.ROADMAP
            }
        map = new google.maps.Map(document.getElementById("map"), mapOptions);
        
        geocoder = new google.maps.Geocoder();
        createAllMarkers();

        if ('' != pre.search) {
            showAddress(pre.search);
        } else if ('' != pre.aid) {
            openPopup(pre.aid);
        }
    });

    // Load Country selectbox
    function loadCountries() {
        if ('' != mapstatus.cc && null != mapstatus.cc) {
            $('select#country option').each(function() {
                if (this.value == mapstatus.cc) {
                    $(this).attr('selected', 'selected');
                }
            });
        }
    }
    loadCountries();
    
    // Load Airbases selectbox
    function loadAirbases(countycode, groupid, offerid) {
        $.post(base_url + 'ajax/airbases', {'cc' : mapstatus.cc, 'gid': mapstatus.gid, 'oid': mapstatus.oid}, function (data) {
            $('select#airbase').children().remove();
            $.each(data, function(key, airbase) {
                var selected;
                if (airbase.cc) {cinfo = ' (' + airbase.cc + ')';} else {cinfo = '';}
                if (airbase.id == mapstatus.aid) {selected = 'selected="selected"';} else {selected = '';}
                $('select#airbase').append('<option value="' + airbase.id + '" ' + selected + ' >' + airbase.city + cinfo + '</option>');
                
//                if (pre.aid) {
//                    openPopup(pre.aid);
//                }
            });
        });
    }
    loadAirbases();
    
    
    // Load Offers selectbox
    function loadOffergroups() {
        $.post(base_url + 'ajax/offergroups', {'cc' : mapstatus.cc, 'gid': mapstatus.gid, 'oid': mapstatus.oid}, function(data) {
            $('select#offer').children().remove();
            $.each(data, function(key, offergroup) {
                var selected;
                if (offergroup.id == mapstatus.gid) {selected = 'selected="selected"';} else {selected = '';}
                $('select#offer').append('<option value="' + offergroup.id + '" '+ selected +' >' + offergroup.name +'</option>');
            });
        });
    }
    loadOffergroups();
    
    

    /****************************************************
     * Event driven part (onclick, onchange,...)
     ***************************************************/

    // load offers if country box has changed
    $('select#country').change( function() {
        mapstatus.cc = $("select#country option:selected").first().val();
        
        // Load Marker Coordinates from json controller and call the map load() function
        $.post(base_url+ 'ajax/markers', {'cc' : mapstatus.cc, 'gid': mapstatus.gid, 'oid': mapstatus.oid} , function(data) {
            $("select#airbase option:selected").each( function() {$(this).removeAttr("selected");})
            infowindow.close();
            
            renewMarkers(data);
        });
        loadAirbases();
    });

    // load offers if country box has changed
    $('select#airbase').change( function() {
        aid = $("select#airbase option:selected").first().val();
        if(aid) {
            $.post(base_url+ 'ajax/markers', {'cc' : mapstatus.cc, 'gid': mapstatus.gid, 'oid': mapstatus.oid}, function(data) {
                infowindow.close();
                renewMarkers(data);
                //show Popup
                openPopup(aid);
            });
        } else {
            //reset "viewport"
            infowindow.close();
            map.setCenter(new google.maps.LatLng(mapstatus.view.lat, mapstatus.view.lng));
            map.setZoom(mapstatus.view.zoom);
        }
    });
    
    // load offers if country box has changed
    $('select#offer').change(function() {
        mapstatus.gid = $("select#offer option:selected").first().val();
        mapstatus.oid = '';
        mapstatus.aid = '';
        
        // refresh Airbases dropdown box
        loadAirbases();
        
        // Load Marker Coordinates
        $.post(base_url+ 'ajax/markers', {'cc' : mapstatus.cc, 'gid': mapstatus.gid, 'oid': mapstatus.oid} , function(data) {
            $("select#airbase option:selected").each(function(){$(this).removeAttr("selected");})
            infowindow.close();
            
            renewMarkers(data);
        });
    });


    // center and zoom on search
    $('input#search').keyup(function(e) {
        // on enter key
        if(e.keyCode == 13) {
            $("select#country option:selected").each(function(){$(this).removeAttr("selected");})
            $("select#airbase option:selected").each(function(){$(this).removeAttr("selected");})
            $("select#offer option:selected").each(function(){$(this).removeAttr("selected");})
            pre.cc = null;
            pre.aid = null;
            $.post(base_url+ 'ajax/markers', function(data) {
                renewMarkers(data);
                loadAirbases();
                var search = $('input#search').val();
                showAddress(search);
            });
        }
    });

    // clear old markers, create new, set center and zoom
    function renewMarkers(data) {

        $.each(airbases, function(key,airbase){
            airbase.marker.setMap(null); 
        });
        
        // recreate them
        airbases = data.markers;
        mapstatus.view = data.view;
        
        createAllMarkers();
        map.setCenter(new google.maps.LatLng(data.view.lat, data.view.lng));
        map.setZoom(data.view.zoom);
    }

    // Custom Marker Icon
    var icon = new google.maps.MarkerImage(
        base_url + 'img/heliicon.gif',
        new google.maps.Size(23, 23),
        new google.maps.Point(0,0),
        new google.maps.Point(12, 12)
        );
    // Custom Marker Shadow
    var shadow = new google.maps.MarkerImage(
        base_url + 'img/heliicon_shadow.png',
        new google.maps.Size(35, 35),
        new google.maps.Point(0,0),
        new google.maps.Point(17, 17)
        );
            
    // InfoWindow with default "loading" Content
    var loading = '<img src="' + base_url + 'img/loading.gif" alt="loading"/><br/><span>informationen werden geladen...</span>';
    var infowindow = new google.maps.InfoWindow({
        content: loading
        });
    google.maps.event.addListener(infowindow, 'closeclick', function() {this.setContent(loading);});
    
    // the function for Custom Marker Clicks
    var markerClick = function(event) {
        if (frontpage) {
            window.location = base_url +'standorte/airbase/'+ this.airbaseid;
        } else {
            $.colorbox({href: base_url +'standorte/airbasedetail/'+ this.airbaseid , width:"800px", height:"667px", initialWidth:"50px", initialHeight:"50px"  });
//            $.ajax(
//                base_url + "standorte/detail/" + this.airbaseid, {
//                    async: false,
//                    success: function(data){
//                        infowindow.setContent(data);
//                }
//            });
//            infowindow.open(map,this);
            map.setCenter(new google.maps.LatLng(this.position.lat(), this.position.lng()));
            map.setZoom(10);
            currentMarker = this;
            
            // reset Airbase Dropdown
            $("select#airbase option:selected").each(function(){$(this).removeAttr("selected");})
            $($("select#airbase option[value="+ this.airbaseid +"]").each(function() {
                $(this).attr("selected","selected");
            }))
        }
    }
    
    /**
     * trigger the 'click' event on the given airbase
     * V3
     */
    function openPopup(airbaseid) {
        theAirbase = null;
        for (var i=0; i <= airbases.length; i++) {
            if (airbases[i] != null) {
                if ( airbases[i].id == airbaseid) {
                    theAirbase = airbases[i];
                    break;
                }
            }
        }
        if (theAirbase != null) {
            google.maps.event.trigger(theAirbase.marker,'click');
        }
    }
   


    /**
     * create all possible markers 
     * V3
     */
    function createAllMarkers() {
        for (var i = 0; i < airbases.length; i++) {
            var airbase = null;
            airbase = airbases[i];
            if (null == airbase) {
                continue;
            }
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(airbase.latitude, airbase.longitude),
                map: map,
                shadow: shadow,
                icon: icon,
                airbaseid: airbase.id
            });
            
            google.maps.event.addListener(marker, 'click', markerClick);
            airbase.marker = marker;
        }
    }
    
    /**
     * search Cities by name, and show the location on the map.
     * V3, Pimped
     */
    function showAddress(address) {
        $.each(searchmarkers, function(key, marker) { 
            marker.setMap(null);
        });
        geocoder.geocode( {'address': address}, function(results, gstatus) {
            if (gstatus == google.maps.GeocoderStatus.OK) {
                
                
                
                //alert(results.length);
                // Filter results. only ['de','at','ch'] are of interrest (atm)
                var filteredResults = $.map(results, function(result,i){
                    var components = result.address_components
                    for (e in components) {
                        var elem = components[e];
                        var c = $.inArray('country', elem.types);
                        if (c > -1) {
                            if ($.inArray(elem.short_name, ['DE','AT','CH']) > -1) {
                                result.cc = elem.short_name.toLowerCase();
                                return result;
                            } else {
                                return null;
                            }
                        }
                    }
                });
                
                $.each(filteredResults, function(key, result) { 
                    var marker = new google.maps.Marker({
                        map: map,
                        position: result.geometry.location,
                        formatted_address : result.formatted_address
                    });
                    google.maps.event.addListener(marker, 'click', function() {
                        var text = this.formatted_address;
                        infowindow.setContent(text);
                        infowindow.open(map,this);
                    } );
                    searchmarkers.push(marker);
                });
                
                if (filteredResults.length == 1) {
                    map.setCenter(filteredResults[0].geometry.location);
                    map.setZoom(9);
                    // popup is on the wrong position
                    //google.maps.event.trigger(searchmarkers[0],'click');
                } else {
                    map.setZoom(6);
                }
                
            } 
        });
    } 
});








