﻿/***************** GoogleMaps Load script ******************/
(function ($) {
    $.fn.makeGoogleMap = function (options) {
        return this.each(function () {
            initialize(this);
        });

        var infoWindow;
        var map;
        var geocoder;
        var markers;
        var results;
        var mc;
        var infowindow;
        var pagecount;
        var currentPage;
        var totalPageCount;

        function initialize(element) {
            var centerCoord = new google.maps.LatLng(52.118372, 4.372149);

            //            if (navigator.geolocation) {
            //                navigator.geolocation.getCurrentPosition(function (position) {
            //                    centerCoord = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            //                });
            //            } 

            results = null;
            currentPage = 1;
            totalPageCount = 0;
            pagecount = 10;

            geocoder = new google.maps.Geocoder();
            var Place = $('#plaats').val();

            infowindow = null;

            var myOptions = {
                zoom: 8,
                center: centerCoord,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                navigationControl: true,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.SMALL,
                    position: google.maps.ControlPosition.TOP_LEFT
                }
            };

            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            infowindow = new google.maps.InfoWindow({
                content: "Loading..."
            });

            $('#search').live('click', function (e) {
                SearchPlace($('#plaats').val());
            });

            $('#plaats').live('keydown', function (e) {
                if (e.keyCode == '13' || e.keyCode == '9') {
                    SearchPlace($('#plaats').val());
                }
            });

            SearchPlace(Place);
        }

        function SearchPlace(Place) {
            if (Place.length > 0) {

                $('.results').html('<ol class="wait"><img alt="Loading" src="/statics/img/global/ajax-loader-map.gif" /><br />&nbsp;&nbsp;Loading...</ol>');
                $('.pagination').html('');
                $('.next-page').html("");
                $('.previous-page').html("");

                geocoder.geocode({ 'address': Place }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var selectedLocation = results[0];

                        point:
                        for (var i = 0; i < results.length; i++) {
                            var currentresult = results[i];
                            for (var ii = 0; ii < currentresult.address_components.length; ii++) {
                                if (currentresult.address_components[ii].short_name == "NL") {
                                    selectedLocation = currentresult;
                                    break point;
                                }
                            }
                        }

                        centerCoord = selectedLocation.geometry.location;
                        map.setCenter(centerCoord);
                        map.setZoom(11);
                        LoadMapContentFromServer(centerCoord);

                    } else {
                        centerCoord = new google.maps.LatLng(52.118372, 4.372149);
                        map.setCenter(centerCoord);
                        map.setZoom(8);
                        LoadMapContentFromServer(null);
                    }
                });
            } else {
                LoadMapContentFromServer(null);
            }
        }

        function SetPage(page) {
            if (page >= 1 && page <= totalPageCount) {
                currentPage = page;

                $('.page-num').removeClass("active");
                $('.page-num[rel=' + currentPage + ']').addClass('active');

                GenerateResultList(results, page);
            }
        }

        function GeneratePagination() {
            $('.results-pagination').html("");
            $('.next-page').html("");
            $('.previous-page').html("");

            var paginationString = "";
            if (results != null)
                totalPageCount = (results.length % pagecount);


            for (var i = 0; i < totalPageCount; i++) {

                var isCurrentPageActive = (i + 1) == currentPage ? "active" : "";

                paginationString += '<a rel=' + (i + 1) + ' class="button page-num ' + isCurrentPageActive + '" href="#">' + (i + 1) + '</a>';

                $('.page-num').live('click', function (e) {
                    var clickedPageNum = $(e.target).text();

                    $('.page-num').removeClass("active");
                    $('.page-num[rel=' + clickedPageNum + ']').addClass('active');

                    SetPage(clickedPageNum);
                });

            }

            $('.next-page').html('<a class="button light-button" href="#">Volgende pagina</a>');
            $('.next-page').die();
            $('.next-page').live('click', function (e) {
                SetPage(currentPage + 1);
            });

            $('.previous-page').html('<a class="button back-button light-button" href="#">Vorige pagina</a>');
            $('.previous-page').die();
            $('.previous-page').live('click', function (e) {
                SetPage(currentPage - 1);
            });

            $('.results-pagination').html(paginationString);
        }


        function GenerateResultList(results, page) {
            if (!page) page = 1;
            var resultString = "";
            for (var i = ((page - 1) * pagecount); i < (page * pagecount); i++) {
                if (results[i] != undefined) {
                    resultString += results[i];
                }
            }
            $('#results').html(resultString);
        }

        function LoadMapContentFromServer(newCenterPoint) {

            var url = "";
            var baseUrl = $(location).attr('href').split('?')[0].replace('#', '');
            if (newCenterPoint == null) {
                url = baseUrl + '/GetSchoolMapDataJson?nocache=' + new Date().getMilliseconds();
            } else {
                url = baseUrl + '/GetSchoolMapDataJson?lat=' + newCenterPoint.lat() + '&lng=' + newCenterPoint.lng() + '&nocache=' + new Date().getMilliseconds();
            }

            $.getJSON(url, function (data) {
                //  var resultString = "";
                var htmlResults = new Array();
                markers = data;
                $.each(markers, function (i, details) {
                    var marker = new google.maps.Marker({
                        title: details.name,
                        position: new google.maps.LatLng(details.location[0], details.location[1]),
                        description: details.description,
                        clickable: true,
                        icon: '/statics/img/global/maps-pin/' + details.icon + '.png',
                        shadow: '/statics/img/global/wellant-pushpin-shadow.png',
                        zIndex: 200
                    });

                    google.maps.event.addListener(marker, 'click', function () {
                        infowindow.setContent(this.description);
                        infowindow.open(map, this);
                    });

                    markers[i] = marker;
                    results = htmlResults;
                    htmlResults.push(details.content);
                });
                GeneratePagination();
                GenerateResultList(htmlResults);

                var MCOptions = { gridSize: 5,
                    styles: [{
                        height: 45,
                        url: "/statics/img/global/cluster-marker.png",
                        width: 45,
                        textColor: 'white'
                    },
                            {
                                height: 45,
                                url: "/statics/img/global/cluster-marker.png",
                                width: 45,
                                textColor: 'white'

                            },
                            {
                                height: 45,
                                url: "/statics/img/global/cluster-marker.png",
                                width: 45,
                                textColor: 'white'
                            },
                            {
                                height: 45,
                                url: "/statics/img/global/cluster-marker.png",
                                width: 45,
                                textColor: 'white'
                            },
                            {
                                height: 45,
                                url: "/statics/img/global/cluster-marker.png",
                                width: 45,
                                textColor: 'white'
                            }]
                };

                if (mc != null) {
                    mc.clearMarkers();
                }
                mc = new MarkerClusterer(map, markers, MCOptions);
            });
        }

    };
})(jQuery);

/***************** Lightbox script ******************/
(function ($) {
    $.fn.lightbox = function (options) {
        return this.each(function () {
            initialize($(this));
        });

        function initialize(element) {
            $('.closeMe').bind('click', function (e) {
                if ($(e.target).parents('.box-wrapper1').length == 0 || $(e.target).hasClass('closeMe')) {
                    $(element).hide();
                }
            });

            $(document).bind('keyup', function (e) {
                if (e.keyCode == 27) {
                    $(element).hide();
                }
            });
        }
    };
})(jQuery);

/***************** Box Scroll script ******************/
(function ($) {
    $.fn.boxscroller = function (options) {
        var defaults = {
            animation: 'easeOutQuad', // define which animation
            duration: 500, // define animation duration
            queue: false // define animation duration
        };
        var options = $.extend(defaults, options);

        return this.each(function () {
            initialize($(this), $(this).css('margin-top').replace("px", ""));
        });

        function initialize(element, marginTopValue) {
            $(window).scroll(function () {
                var currentMargin = parseInt(marginTopValue) + parseInt($(window).scrollTop());
                element.stop().animate({ marginTop: currentMargin + 'px' }, { queue: options.queue, duration: options.duration, easing: options.animation });
            });
        }
    };
})(jQuery);

/***************** Accordeon control script ******************/
(function ($) {
    $.fn.acordeon = function (options) {
        var defaults = {
            disable: 0
        };
        var options = $.extend(defaults, options);

        return this.each(function () {
            initialize(this);
        });
        function initialize(element) {
            //Defaults
            $(element).find(".toggle_container").hide();
            $(element).find(".toggle_container:first").show();
            $(element).find("h6.trigger:first").addClass("active");

            $(element).find("h6.trigger").click(function () {
                if (!$(this).hasClass("active")) {
                    $(element).find(".active").toggleClass("active").next().animate({ height: 'toggle' }, { duration: 300, specialEasing: { height: 'easeOutQuad'} }, 300);
                }

                $(this).toggleClass("active").next().animate({ height: 'toggle' }, { duration: 300, specialEasing: { height: 'easeOutQuad'} }, 300);

            });
        }
    };
})(jQuery);

/***************** Carousel control script ******************/
/* Caution! Do not replace with original version ! */
/* This script altered while implementing */

/*
* Tiny Carousel 1.76
*
* Copyright (c) 2010 Maarten Baijs
*
* Date: 01 / 07 / 2010
* Library: jQuery
*
*/
(function ($) {
    $.fn.tinycarousel = function (options) {
        var defaults = {
            start: 1, // where should the carousel start?
            display: 1, // how many blocks do you want to move at 1 time?
            axis: 'x', // vertical or horizontal scroller? ( x || y ).
            controls: true, // show left and right navigation buttons.
            pager: false, // is there a page number navigation present?
            interval: false, // move to another block on intervals.
            intervaltime: 7500, // interval time in milliseconds.
            animation: true, // false is instant, true is animate.
            duration: 650, // how fast must the animation move in ms?
            callback: null, // function that executes after every move
            showtooltip: false // function that executes after every move
        };
        var options = $.extend(defaults, options);
        var oSlider = $(this);
        var oViewport = $('.viewport', oSlider);
        var oContent = $('.images', oSlider);
        var oPages = oContent.children();
        var oBtnNext = $('.next', oSlider);
        var oBtnPrev = $('.prev', oSlider);
        var oPager = $('.pagination', oSlider);
        var oTooltip = $('#tooltip', oSlider);
        var iPageSize, iSteps, iCurrent, oTimer, bForward = true, bAxis = options.axis == 'x';

        return this.each(function () {
            initialize();
        });
        function initialize() {
            iPageSize = bAxis ? $(oPages[0]).outerWidth(true) : $(oPages[0]).outerHeight(true);
            var iLeftover = Math.ceil(((bAxis ? oViewport.outerWidth() : oViewport.outerHeight()) / (iPageSize * options.display)) - 1);
            iSteps = Math.max(1, Math.ceil(oPages.length / options.display) - iLeftover);
            iCurrent = Math.min(iSteps, Math.max(1, options.start)) - 2;
            oContent.css(bAxis ? 'width' : 'height', (iPageSize * oPages.length));

            $.each($(".viewport"), function (index, value) {
                $(value).mouseenter(function () {
                    clearInterval(oTimer);
                });
                $(value).mouseleave(function () {
                    setTimer(false);

                });
            });
            setTooltip();
            move(1);
            setEvents();
        }
        function setTooltip() {
            oTooltip.hide();
            $('.page', oPager).each(function () {
                $(this).hover(
                  function () {
                      if (!$('a', this).hasClass('active')) {

                          var itemNumber = parseInt($('a', this).attr('rel')) + 1;
                          var hoveredItem = $('li:nth-child(' + itemNumber + ')', oContent);

                          $('.inner', oTooltip).html($('.tooltipdata', hoveredItem).html());
                          oTooltip.css('left', $(this).position().left - (oTooltip.width() / 2) + 13);
                          oTooltip.show();
                      }
                  },
                  function () {
                      oTooltip.hide();
                  }
                );
            });
        }
        function setButtons() {
            if (options.controls) {
                oBtnPrev.toggleClass('disable', !(iCurrent > 0));
                oBtnNext.toggleClass('disable', !(iCurrent + 1 < iSteps));
            }
        }
        function setEvents() {
            if (options.controls && oBtnPrev.length > 0 && oBtnNext.length > 0) {
                oBtnPrev.click(function () { move(-1); return false; });
                oBtnNext.click(function () { move(1); return false; });
            }
            if (options.pager && oPager.length > 0) {
                oPager.click(setPager);
            }
        }
        function setPager(oEvent) {
            var oTarget = oEvent.target;
            if ($(oTarget).hasClass('page-num')) {
                iCurrent = parseInt(oTarget.rel) - 1;
                move(1);
            }
            return false;
        }
        function setPagerActive() {
            if (options.pager) {
                var oNumbers = $('.page-num', oPager);
                oNumbers.removeClass('active');
                $(oNumbers[iCurrent]).addClass('active');
            }
        }
        function setTimer(bReset) {
            if (options.interval && !bReset) {
                clearInterval(oTimer);
                oTimer = window.setInterval(function () {
                    bForward = iCurrent + 1 == iSteps ? false : iCurrent == 0 ? true : bForward; //back
                    if (bForward) {
                        move(bForward ? 1 : -1, true);
                    } else {
                        iCurrent = Math.min(iSteps, Math.max(1, options.start)) - 2;
                        move(1);
                    }
                }, options.intervaltime);
            }
        }
        function move(iDirection, bTimerReset) {
            if (iCurrent + iDirection > -1 && iCurrent + iDirection < iSteps) {
                iCurrent += iDirection;
                var oPosition = {};
                oPosition[bAxis ? 'left' : 'top'] = -(iCurrent * (iPageSize * options.display));
                oContent.animate(oPosition, {
                    queue: false,
                    duration: options.animation ? options.duration : 0,
                    easing: "easeOutQuad",
                    complete: function () {
                        if (typeof options.callback == 'function')
                            options.callback.call(this, oPages[iCurrent], iCurrent);
                    }
                });
                setButtons();
                setPagerActive();
                setTimer(bTimerReset);
            }
        }
    };
})(jQuery);
