/// <reference path="jquery-1.5.1.min.js" />
var appGlobal = {
    windlgcounter: 0,
    loaderShow: function () {
        $("#dataloader").center().show();
    },
    loaderHide: function () {
        $("#dataloader").hide();
    },
    bgShow: function () {
        this.windlgcounter += 1;
        var dh = $(document).height();
        $("#modalBG")
            .height(dh)
            .show();
    },
    bgHide: function () {
        this.windlgcounter -= 1;
        if (this.windlgcounter < 1) $("#modalBG").hide();
    },
    getData: function (url, data, onsucces, onerror) {

        data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            data: data,
            async: true,
            cache: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Fout opgetreden op de server.")
                if ($.isFunction(onerror)) onerror();
                appGlobal.loaderHide();
            },
            success: function (retval, r) {
                if (retval.state == true) {
                    if ($.isFunction(onsucces)) onsucces((retval.data) ? retval.data : null);
                } else {
                    if (data.errortype == 'Unauthorized') {
                        hollandgroen.ShowUnauthorizedWindow();
                    } else {
                        alert(retval.error);
                    };
                    if ($.isFunction(onerror)) onerror();
                };
            }
        }); //eof  ajax

        // dispose locals
        SendData = null;
    },

    getHtml: function (url, data, onsucces, onerror) {

        data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'html',
            data: data,
            async: true,
            cache: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Fout opgetreden op de server.")
                if ($.isFunction(onerror)) onerror();
                appGlobal.loaderHide();
            },
            success: function (retval, r) {
                if ($.isFunction(onsucces)) onsucces((retval) ? retval : null);
            }
        }); //eof  ajax

        // dispose locals
        SendData = null;
    }
};

// ------------------------------------------------------------------------------------
// Center a div
// ------------------------------------------------------------------------------------
(function ($) {
    jQuery.fn.center = function (o) {
        if (o) {
            this.css("position", "absolute");
            this.css("margin-top", (o.height() - this.height()) / 2 + "px");
            this.css("margin-left", (o.width() - this.width()) / 2 + "px");
            return this;
        } else {
            this.css("position", "absolute");
            this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
            this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
            return this;
        };
    };
})(jQuery);
// ------------------------------------------------------------------------------------

// ------------------------------------------------------------------------------------
// slides plugin for jquery
// ------------------------------------------------------------------------------------
(function ($) {

    $.fn.slides = function (options) {

        // settings for pliging
        var settings = {
            slidedelay: 2000,
            slidefadedelay: 300
        };

        // ge all slides
        var slides = this.find('.slide');

        // local stack for counters
        var slidenr_curr = 0;
        var slidenr_prev = -1;

        // methods of pluging
        var methods = {

            setcurrent: function () {

                // timernext
                slidenr_prev = slidenr_curr;
                slidenr_curr += 1;
                if (slidenr_curr == slides.length) slidenr_curr = 0;
                setTimeout(methods.shownext, settings.slidedelay);

            },

            shownext: function () {

                // load image
                var img = new Image();

                if ($(slides[slidenr_curr]).attr('isloaded') == 0) {
                    // load image
                    $(img).load(
                        function () {
                            // create image....
                            $(slides[slidenr_curr]).append($(img))
                                                   .attr('isloaded', 1);
                            // show first time
                            if (slidenr_prev < 0) {
                                $(slides[slidenr_curr]).fadeIn(settings.slidefadedelay, function () { methods.setcurrent(); })
                            } else {
                                $(slides[slidenr_prev]).fadeOut(settings.slidefadedelay);
                                $(slides[slidenr_curr]).fadeIn(function () { methods.setcurrent(); });
                            };

                        })
                    .error(function () {
                        alert("Error img load");
                    })
                    .attr('src', $(slides[slidenr_curr]).attr('value'));
                } else {
                    // show
                    $(slides[slidenr_prev]).fadeOut(settings.slidefadedelay);
                    $(slides[slidenr_curr]).fadeIn(function () { methods.setcurrent(); });

                };

            }
        };

        // Maintaining Chainability
        return this.each(function () {

            // If options exist, merge them with default settings
            if (options) {
                $.extend(settings, options);
            }

            // If there are slides show slides
            if (slides.length > 0) {

                methods.shownext();

            };

        });

    };

})(jQuery);
// ------------------------------------------------------------------------------------


// ------------------------------------------------------------------------------------
// PagerClass
// Bij bladeren van foto's wordt er van dit object gebruik gemaakt om cliensite
// paginanummers weer te geven en te kunnen bladeren
// ------------------------------------------------------------------------------------
function PagerCls() { }

PagerCls.prototype.Totalrows = 0;
PagerCls.prototype.TotalPages = 0;
PagerCls.prototype.PageSize = 8;
PagerCls.prototype.ShowPages = 6;
PagerCls.prototype.CurrentPage = 1;
PagerCls.prototype.NextPage = 0;
PagerCls.prototype.PrevPage = 0;

// buildpager
PagerCls.prototype.GetPager = function (baseclsname) {

    var pFirst = 1;
    var pLast = this.TotalPages;

    if (this.TotalPages > this.ShowPages) {

        var CenterOfPage = Math.ceil(this.ShowPages / 2);

        pFirst = this.CurrentPage - CenterOfPage;
        pLast = this.CurrentPage + CenterOfPage;

        if (pFirst < 1) {
            pFirst = 1;
            pLast = this.ShowPages + 1;
        };

        if (pLast > this.TotalPages) {
            pFirst = this.TotalPages - this.ShowPages;
            pLast = this.TotalPages;
        };
    };

    var s = new Array();
    s[s.length] = '<div class="pager">';
    s[s.length] = '<span class="ipager">' + this.Totalrows + ' foto\'s - Pagina ' + this.CurrentPage + ' van ' + this.TotalPages + '</span> ';
    for (var p = pFirst; p <= pLast; p++) {
        if (p == this.CurrentPage) {
            s[s.length] = '<span class="cpager">' + p + '</span>';
        } else {
            s[s.length] = '<a href="" class="npager" onclick="' + baseclsname + '.getPage(' + p + '); return false;">' + p + '</a>&nbsp;';
        };
        if (p == pLast && p < this.TotalPages) {
            s[s.length] = '<span class="lpager">...</span>&nbsp;';
        };
    };
    s[s.length] = '</div>';

    return s.join('');

};    // eo GetPager

// Update pager after new received data
PagerCls.prototype.SetTotalrows = function (i) {
    this.Totalrows = i;
    this.TotalPages = Math.ceil(this.Totalrows / this.PageSize);
    this.NextPage = this.CurrentPage + 1;
    this.PrevPage = this.CurrentPage - 1;
    if (this.PrevPage < 1) {
        this.PrevPage = 1;
    };
    if (this.NextPage > this.TotalPages) {
        this.NextPage = 1;
    };
};  // eo Update
// EO PagerClass
// ------------------------------------------------------------------------------------


// ------------------------------------------------------------------------------------
// WinAnimClass
// Voert animaties uit zoom in zoom uit
// ------------------------------------------------------------------------------------
function WinAnimClass() {
    //baseclass to use in different scopes
    var BClass = this;

    //needed in stringbuilder 
    this.BClassName = "";

    // window container
    this.$body = $('#zoominbox');

    // from dimensions
    this.AniFrom = {
        left: 0,
        top: 0,
        width: 0,
        height: 0
    };

    // To dimensions
    this.AniTo = {
        left: 0,
        top: 0,
        width: 0,
        height: 0
    };

    this.zoomIn = function () {

        BClass.$body.show();

        this.$body
            .animate({
                'opacity': 1,
                'left': this.AniFrom.left,
                'top': this.AniFrom.top,
                'width': this.AniFrom.width,
                'height': this.AniFrom.height
            }, function () {
                BClass.$body.hide();
            });
    };


    this.zoomOut = function ($from, $To, onAfterZoom) {

        this.$body = $('#zoominbox');

        // set from parent zoom
        this.AniFrom.left = $from.offset().left;
        this.AniFrom.top = $from.offset().top;
        this.AniFrom.width = $from.outerWidth();
        this.AniFrom.height = $from.outerHeight();

        // set from parent zoom
        this.AniTo.width = $To.outerWidth();
        this.AniTo.height = $To.outerHeight();
        this.AniTo.left = ($(window).width() - this.AniTo.width) / 2 + $(window).scrollLeft();
        this.AniTo.top = ($(window).height() - this.AniTo.height) / 2 + $(window).scrollTop();

        // set picholder over image needed for zoom effect
        this.$body
            .width(this.AniFrom.height)
            .height(this.AniFrom.width)
            .css('left', this.AniFrom.left)
            .css('top', this.AniFrom.top);

        this.$body
            .show()
            .animate({
                'opacity': 1,
                'left': this.AniTo.left,
                'top': this.AniTo.top,
                'width': this.AniTo.width,
                'height': this.AniTo.height
            }, function () {

                BClass.$body.hide();

                if ($.isFunction(onAfterZoom)) {
                    onAfterZoom();
                };

            });
    };
};

// ------------------------------------------------------------------------------------
// Show picture
// Voert animaties uit zoom in zoom uit
// ------------------------------------------------------------------------------------
(function ($) {

    $.fn.picview = function () {

        var me = this;

        var picwin = $('#picwin');
        var picwinimg = picwin.find('.picwin-pic img');
        var picwinmnu = picwin.find('.picwin-mnu');
        var eventtarget = $([]);

        // init click event
        me.click(function () {
            eventtarget = $(this);
            methods.show($(this).attr('valueurl'));
        });

        var picsize = {
            w: 0,
            h: 0
        };

        // animation handler
        var AnimHandler = new WinAnimClass();

        // methods of pluging
        var methods = {

            // Event handlers. resize window dialog on browser resize
            winResizeHandler: function () {
                methods.resize();
            },

            // Event handlers. resize window dialog on browser scroll
            winScrollHandler: function () {
                methods.resize();
            },

            createwin: function () {


            },

            enablewindow: function () {

                picwin.show();

                methods.resize();

                // bind events for resize on window size change
                $(window).bind('resize', methods.winResizeHandler)
                         .bind('scroll', methods.winScrollHandler);

                picwinmnu.find('#btnClose').click(
                    function () {
                        methods.close();
                    }
                );
                picwinimg.click(
                    function () {
                        methods.close();
                    }
                );

            },

            close: function () {

                // unbind events for resize on window size change
                $(window).unbind('resize', methods.winResizeHandler)
                         .unbind('scroll', methods.winScrollHandler);
                // unbind click event
                picwinmnu.find('#btnClose').unbind('click');
                picwinimg.unbind('click');
                picwin.hide();
                appGlobal.bgHide();
                AnimHandler.zoomIn();

            },

            resize: function (width, height) {

                var imgW = picsize.w;
                var imgH = picsize.h;

                var ResizeImg = false;

                if (imgW > $(window).width()) imgW = $(window).width() - 10; ;
                if (imgH > $(window).height()) imgH = $(window).height() - 10;

                // resize image
                if (imgW > imgH) {
                    // horizontal image
                    var imWPercentage = imgW / (picwinimg.width());
                    imgH = Math.round(picsize.h * imWPercentage);
                } else {
                    // vertical image
                    var imHPercentage = imgH / (picwinimg.height());
                    imgW = Math.round(picsize.w * imHPercentage);
                };


                picwinimg.height(imgH)
                         .width(imgW);

                picwinmnu.css('left', (imgW / 2) - (picwinmnu.width() / 2))
                         .css('top', imgH - picwinmnu.height() - 2);

                picwin.height(imgH)
                      .width(imgW)
                      .center();
            },

            // zoom to picture    
            show: function (src) {

                // loader
                appGlobal.loaderShow();

                // init image
                var img = new Image();

                // load image
                $(img).load(
                    function () {

                        // set originalsize
                        picsize.w = img.width;
                        picsize.h = img.height;

                        picwinimg.attr('src', img.src)
                                 .css('cursor', 'pointer');
                        picwinmnu.css('cursor', 'pointer');

                        // hide loader
                        appGlobal.loaderHide();
                        appGlobal.bgShow();


                        // resize to images
                        AnimHandler.zoomOut(eventtarget, picwin, function () {
                            methods.enablewindow();
                        });

                    })
                    .error(function () {
                        alert("Error img load");
                    })
                    .attr('src', src);

            }

        };

        // Maintaining Chainability
        return this.each(function () {

        });

    };

})(jQuery);

