﻿/// <reference path="../../jquery-1.5.1.min.js" />
/// <reference path="../../Global/globalscripts.js" />

// ------------------------------------------------------------------------------------
// WinGMAPClass
// showmap with natures
// ------------------------------------------------------------------------------------
function WinGMAPClass() {
    //baseclass to use in different scopes
    var BClass = this;

    // animation handler
    this.AnimHandler = new WinAnimClass();

    // window container
    this.$body = $('#naturemap');

    this.isloaded = false;

    // map 
    this.GMap = null;
    // geocoder
    this.GGeocoder = null;
    // infowindow
    this.InfoWindow = null;

    // marker manager
    this.MarkerMngr = null;
    this.ZoomFactor = 8;

    // Icons for home marker
    this.MarkerIcons = {
        Home: '/Content/images/naturemap/icon-home.gif',
        Visited: '/Content/images/naturemap/icon-nature.gif',
        Notvisited: '/Content/images/naturemap/icon-nature-disabled.gif',
        NationalPark: '/Content/images/naturemap/icon-np.gif'
    };

    // Event handlers. resize window dialog on browser resize
    // ------------------------------------------------------------------------------------
    var winGMAPResizeHandler = function () {
        BClass.SetResize();
    };

    // Event handlers. resize window dialog on browser scroll
    // ------------------------------------------------------------------------------------
    var winGMAPScrollHandler = function () {
        BClass.SetResize();
    };


    // dispose all locals such bind events
    // ------------------------------------------------------------------------------------
    this.SetResize = function () {
        winW = 1000; // 1000 pix groot
        winH = 893;

        if (winW > $(window).width()) winW = $(window).width() - 10;
        if (winH > $(window).height()) winH = $(window).height() - 15;

        this.$body.width(winW);
        this.$body.height(winH);

        // set title geo
        this.$body.find('#naturemap-top').width(winW);
        this.$body.find('#naturemap-top .naturemap-top-title').width(winW - 261);

        // set width body parts
        this.$body.find('#maptab').width(winW - 249 - 2);
        this.$body.find('#maptab-help').width(winW - 249 - 2);

        // set height body parts
        this.$body.find('#maptab-map').height(winH - 34); // = 249px 252px  
        this.$body.find('#maptab-map #searchfilter').height(winH - 328); // = 249px

        this.$body.find('#maptab').height(winH - 34);
        this.$body.find('#maptab #mapholder').height(winH - 34);
        this.$body.find('#maptab-help').height(winH - 34);

        this.$body.center();

    };     //eo SetResize 

    // dispose all locals such bind events
    // ------------------------------------------------------------------------------------
    this.WinDlgDispose = function () {

        BClass.$body.hide();

        // global  loading div hide
        hollandgroen.LoaderHide();
        hollandgroen.BackGroundHide();

        this.AnimHandler.zoomIn();

        $(window).unbind('resize', winGMAPResizeHandler)
                 .unbind('scroll', winGMAPScrollHandler);

    };  // WinDlgDispose


    // Initialize
    // ------------------------------------------------------------------------------------
    this.Initialize = function () {

        // already loadded do not reinit
        if (!this.isloaded) {

            // init tab buttons
            this.$body.find('#naturemap-top-tabs div').click(function () {
                switch ($(this).attr('id')) {
                    case 'tab-map':
                        $('#maptab').show();
                        $('#maptab-help').hide();
                        break;
                    case 'tab-help':
                        $('#maptab').hide();
                        $('#maptab-help').show();
                        break;
                    case 'tab-close':
                        BClass.WinDlgDispose();
                        break;
                };
            });

            this.$body.find('#naturemap-top-tabs div').hover(function () {
                $(this).addClass('tab-hover').removeClass('tab');
            }, function () {
                $(this).addClass('tab').removeClass('tab-hover');
            });

            this.$body.find('#GmapBtnSearch').click(
                function () {
                    // show loader
                    hollandgroen.LoaderShow();
                    
                    // BClass.MarkerMngr.clearMarkers();

                    // change viewport for country
                    BClass.getCountryView(BClass.$body.find('#GmapCountryId :selected').text());
                    // submit search frm
                    BClass.GetMarkersOfNatures();
                });

            // on country change update new provinces
            this.$body.find('#GmapCountryId').change(function () {

                // BClass.MarkerMngr.clearMarkers();

                var $Provinces = $('#GmapProvincieId');

                // update new values by ajax
                var senddata = new Object;
                senddata.CountryId = $(this).val();

                // send to server
                hollandgroen.Getdata('/DataConn/GetProvincesInNature', senddata,
                function (retdata) {
                    // update provinces selectbox
                    hollandgroen.LoaderHide();

                    // change viewport for country
                    BClass.getCountryView(BClass.$body.find('#GmapCountryId :selected').text());

                    // refresh markers
                    BClass.GetMarkersOfNatures();

                    $Provinces.find('option').remove()
                        .end()
                        .append('<option value="-1">-- Selecteer --</option>');
                    for (var i = 0; i < retdata.length; i++) {
                        $Provinces.append('<option value="' + retdata[i].ProvinceId + '">' + retdata[i].Province_Name + '</option>');
                    };

                });
            });

            // set size of map window
            BClass.SetResize();

        } else {

        };

        // always first tab to show is map tab
        $('#maptab').show();
        $('#maptab-help').hide();

        // set on resize handlers
        $(window).bind('resize', winGMAPResizeHandler);
        $(window).bind('scroll', winGMAPScrollHandler);

    };

    // homemarker
    this.createHomeMarker = function (data) {

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data.Lat, data.Lng),
            title: 'Uw thuislocatie',
            map: BClass.GMap,
            icon: BClass.MarkerIcons.Home
        });

        // dispose

        return HomeMarker;
    };

    // createMarker
    // ------------------------------------------------------------------------------------
    this.createMarker = function (nature) {

        var icon = BClass.MarkerIcons.Notvisited;
        if (nature.IsVisited) icon = BClass.MarkerIcons.Visited;
        if (nature.NatureCategoryID == 2) icon = BClass.MarkerIcons.NationalPark;

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(nature.Latitude, nature.Longitude),
            title: nature.Title,
            // map: BClass.GMap,
            icon: icon
        });

        var sHtml = new Array();
        sHtml[sHtml.length] = '<div style="color:black;">'
        sHtml[sHtml.length] = '<b>' + nature.Title + '</b><br/>';
        sHtml[sHtml.length] = 'Beheerder: ' + nature.NatureCategoryTitle + '<br/>';
        sHtml[sHtml.length] = '<a href="/Natuurgebieden/' + nature.NatureUrl + '">Meer info</a><br/>';
        sHtml[sHtml.length] = '</div>';
        marker.Htmltxt = sHtml.join('');

        google.maps.event.addListener(marker, 'click',
                            function () {
                                if (BClass.InfoWindow) BClass.InfoWindow.close();
                                BClass.InfoWindow.setContent(marker.Htmltxt);
                                BClass.InfoWindow.open(BClass.GMap, marker);
                            });


        // dispose
        icon = null
        sHtml = null;

        return marker;
    }; // eo createMarker


    // Process Visited Natures
    // ------------------------------------------------------------------------------------
    this.ProcessVisitedNatures = function (data) {

        // clear current markers...
        this.MarkerMngr.clearMarkers();

        // counter amount of visited natures
        var CountVisit = 0
        var markerVisits = [];

        // loop natures
        for (var i = 0; i < data.NatureList.length; i++) {

            // insert in array
            markerVisits.push(this.createMarker(data.NatureList[i]));

            // count visited nature
            if (data.NatureList[i].IsVisited == true) CountVisit += 1;

        };

        this.$body.find("#mapVisited").html('Totaal bezocht: ' + CountVisit);
        this.$body.find("#mapTotal").html('Aantal: ' + data.NatureList.length);

        // add markers on map
        this.MarkerMngr.addMarkers(markerVisits, 1);

        // update gmap
        this.MarkerMngr.refresh();

        // dispose locals
        markerVisits = null;

        hollandgroen.LoaderHide();

    }; // EO ProcessVisitedNatures

    // ------------------------------------------------------------------------------------
    // GetMarkersOfNatures
    this.GetMarkersOfNatures = function () {

        // load frm
        var senddata = new Object();
        senddata.GmapSearchName = $('#GmapSearchName').val();
        senddata.GmapCountryId = $('#GmapCountryId').val();
        senddata.GmapProvincieId = $('#GmapProvincieId').val();
        senddata.GmapIsVisited = $('#GmapIsVisited').val();
        senddata.GmapNatureCategoryId = $('#GmapNatureCategoryId').val();

        // get properties
        var $nprops = $('input[name="naturemappropfilter"]:checked');
        var proplist = '';
        if ($nprops.length > 0) {
            for (i = 0; i < $nprops.length; i++) {
                if (proplist != '') proplist += ",";
                proplist += $nprops[i].value;
            };
        };
        senddata.GmapSearchPropertyIds = proplist;

        // get data by ajax
        hollandgroen.Getdata('/DataConn/BezochtNatuur'
                             , senddata
                             , function (retval) {
                                 BClass.ProcessVisitedNatures(retval);
                             });
        SendData = null;

    }; // eo GetMarkersOfNatures

    // getAdresseLatLng
    // get lat and lng for addresse
    // ------------------------------------------------------------------------------------
    this.getCountryView = function (country) {

        if (country.length > 0 && this.GGeocoder) {

            // get adres latlng
            this.GGeocoder.geocode({ 'address': country },
                function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {

                        // center map to the country
                        var centre = results[0].geometry.viewport.getCenter();
                        BClass.GMap.setCenter(results[0].geometry.viewport.getCenter());

                        // fit viewport on country
                        BClass.GMap.fitBounds(results[0].geometry.viewport);

                    } else {
                        alert("Ophalen van adres coordinaten mislukt. Fout: " + status);
                    };
                }
            );
        };
    };

    // ------------------------------------------------------------------------------------
    // Show
    this.ActivateWindow = function (fromobject) {

        this.AnimHandler.zoomOut($(fromobject), BClass.$body,
                    function () {

                        // show first tab
                        $('#maptab-help').hide();
                        $('#maptab-map').show();

                        BClass.$body.show().center();

                        // show modal background
                        hollandgroen.BackGroundShow();

                        if (!BClass.isloaded) {
                            // Google Maps
                            var latlng = new google.maps.LatLng(52.18550896060775, 5.293192265625084);
                            var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.TERRAIN };
                            BClass.GMap = new google.maps.Map(document.getElementById("mapholder"), myOptions);

                            // Marker manager
                            var mgrOptions = { borderPadding: 50, maxZoom: 15, trackMarkers: false };
                            BClass.MarkerMngr = new MarkerManager(BClass.GMap, mgrOptions);

                            BClass.InfoWindow = new google.maps.InfoWindow({ content: '' });

                            // init geocoder
                            BClass.GGeocoder = new google.maps.Geocoder();

                            var listener = google.maps.event.addListener(BClass.GMap, 'bounds_changed',
                                function () {
                                    // get markers
                                    BClass.GetMarkersOfNatures();
                                    google.maps.event.removeListener(listener);
                                }
                            );

                            BClass.isloaded = true;

                            // dispose
                            myOptions = null;
                            mgrOptions = null;

                        };

                    }
        ); // eo anim

    };      // eo ActivateWindow


    // ------------------------------------------------------------------------------------
    // Show
    this.Show = function (fromobject) {

        // init base div
        this.$body = $('#naturemap');

        // is html loaded
        if (!this.isloaded || this.$body.length < 1) {

            hollandgroen.LoaderShow();

            // get html
            hollandgroen.Gethtml('/Pagepart/popGMAP', {}
                                 , function (retVal) {

                                     // load window 
                                     $('#MainCache').append(retVal);

                                     // find win body of map
                                     BClass.$body = $('#naturemap');

                                     BClass.IsLoaded = true;

                                     // init map
                                     BClass.Initialize();

                                     BClass.ActivateWindow(fromobject);

                                 });

        } else {

            // show window...
            this.ActivateWindow(fromobject);

        };

    };

};
