﻿/// <reference path="../jquery-1.4.4.min.js" />
/// <reference path="../jquery.ui/jquery-ui-1.8.9.custom.min.js" />
/// <reference path="../jquery.validate.js" />
/// <reference path="../jquery.validate.unobtrusive.js" />

var hollandgroen = {
    cachedivname: 'MainCache',
    windlgcounter: 0,
    LoaderShow: function () {
        $("#dataloader").center().show();
    },
    LoaderHide: function () {
        $("#dataloader").hide();
    },
    BackGroundShow: function () {
        this.windlgcounter += 1;
        var dh = $(document).height();
        $("#modalBG")
            .height(dh)
            .show();
    },
    BackGroundHide: function () {
        this.windlgcounter -= 1;
        if (this.windlgcounter < 1) $("#modalBG").hide();
    },
    AjaxDataResult:
    {
        state: null,
        errmsg: null,
        data: null
    },

    IsAuthorized: function () {
        var isok = false;
        // show loader
        hollandgroen.LoaderShow();
        data = new Object();
        data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

        $.ajax({
            url: '/Account/IsAuthorized',
            type: 'POST',
            dataType: 'json',
            data: data,
            async: false,
            cache: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Fout opgetreden op de server.")
            },
            success: function (retval, r) {
                if (retval.state == true) {
                    hollandgroen.LoaderHide();
                    if (retval.data == true) {
                        isok = true;
                    } else {
                        isok = false;
                    };
                } else {
                    if (data.errortype == 'Unauthorized') {
                        hollandgroen.ShowUnauthorizedWindow();
                    } else {
                        alert(retval.error);
                    };
                    hollandgroen.LoaderHide();
                    isok = false;
                };
            }
        }); //eof  ajax

        return isok;
    },

    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();
            },
            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();
            },
            success: function (rethtml, r) {
                if ($.isFunction(onsucces)) onsucces(rethtml);
            }
        }); //eof  ajax

        // dispose locals
        SendData = null;
    },
    ShowUnauthorizedWindow: function () {

        var $swin = $('#MainCache #UnauthorizedWindow');
        if ($swin.length < 1) {
            var s = new Array();
            s[s.length] = '<div id="UnauthorizedWindow" class="WinDlg">';
            s[s.length] = '<div class="wintitle">Helaas alleen voor geregistreerde gebruikers.</div>';
            s[s.length] = '<div class="wbody">';
            s[s.length] = '<div class="wbody-body">';
            s[s.length] = '<h2><img src="/Content/images/Info.png" align="absmiddle" alt="Waarschuwing"/> Helaas alleen voor geregistreerde gebruikers.</h2>';
            s[s.length] = '<p>Je moet eerst <a href="/Account/Inloggen">inloggen</a> om een reactie te kunnen plaatsen. ';
            s[s.length] = 'Je kan inloggen door hier te <a href="/Account/Inloggen">klikken</a>.</p>';
            s[s.length] = '<p>Wachtwoord vergeten? Geen punt, vraag <a href="/Account/ResetPassword">hier</a> een nieuw wachtwoord aan.</p>';
            s[s.length] = '<p>Heb je nog geen account bij hollandgroen.nl? Geen paniek, je kan je ';
            s[s.length] = '<a href="/Account/Registreren">gratis registreren</a> door ';
            s[s.length] = '<a href="/Account/Registreren">dit formulier</a> in te vullen en binnen een minuut kun je hier inloggen.</p>';
            s[s.length] = '<p style="text-align:center;"><input type="button" value="Sluiten" id="UnauthorizedWindow-btClose"  /></p>';
            s[s.length] = '</div>';
            s[s.length] = '</div>';
            s[s.length] = '</div>';

            // create window
            $('#MainCache').append(s.join(''));

            $swin = $('#MainCache #UnauthorizedWindow');

            // set size..
            $('#UnauthorizedWindow').width(561);
            $('#UnauthorizedWindow').height(323);
            $('#UnauthorizedWindow .wbody').width(560);
            $('#UnauthorizedWindow .wbody').height(288);
            $('#UnauthorizedWindow .wbody .wbody-body').width(539);

        };

        s = null;

        if ($swin.length > 0) {
            // show modal dialog bk
            this.BackGroundShow();
            // init event
            $('#UnauthorizedWindow-btClose').click(
                function () {
                    $swin.hide();
                    hollandgroen.BackGroundHide();
                    $('#UnauthorizedWindow-btClose').unbind('click');
                }
            );

            $swin.center().show();
        };
    }

}

// ------------------------------------------------------------------------------------
// MetaTagClass
// Bij aanmaken van webpagina worden de metatags hiermee gecontroleerd.
// ------------------------------------------------------------------------------------
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;
    };
};

// ------------------------------------------------------------------------------------
// WinAnimClass
// Voert animaties uit zoom in zoom uit
// ------------------------------------------------------------------------------------
function AnimatorClass() {
    //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();
                };

            });
    };
};


// ------------------------------------------------------------------------------------
// MetaTagClass
// Bij aanmaken van webpagina worden de metatags hiermee gecontroleerd.
// ------------------------------------------------------------------------------------
function ButtonILikeClass() {
    //baseclass to use in different scopes
    var BClass = this;
    var BClassName = '';

    // SetBlog
    // ------------------------------------------------------------------------------------
    this.SetBlog = function (id, $lnk) {

        // Get Comment formdata
        var senddata = new Object();
        senddata["id"] = id;

        // get data by ajax
        hollandgroen.Getdata('/Blogs/SetILike'
                             , senddata
                             , function (retval) {
                                 hollandgroen.LoaderHide();
                                 if (retval.action == 'del') {
                                     $lnk.html('Vind ik leuk.')
                                 } else {
                                     $lnk.html('Vind ik niet meer leuk')
                                 };

                                 var sHTML = new Array();
                                 if (retval.html != '') {
                                     sHTML[sHTML.length] = '<div class="blogIlikes">';
                                     sHTML[sHTML.length] = (retval.html) ? retval.html : '';
                                     sHTML[sHTML.length] = '</div>';
                                 };

                                 $lnk.parent().parent().find('.blogIlikesHold').html(sHTML.join(''));

                             }, function (retval) {
                                 hollandgroen.LoaderHide();
                             }
        ); // EO hollandgroen.Getdata

        pName = null;
        pCat = null;

    }

    // SetPic
    // ------------------------------------------------------------------------------------
    this.SetPic = function (id, $lnk) {

        // Get Comment formdata
        var senddata = new Object();
        senddata["id"] = id;

        // get data by ajax
        hollandgroen.Getdata('/Fotos/SetILike'
                             , senddata
                             , function (retval) {

                                 hollandgroen.LoaderHide();

                                 if (retval.action == 'del') {
                                     $lnk.html('Vind ik leuk.')
                                 } else {
                                     $lnk.html('Vind ik niet meer leuk')
                                 }
                                 var sHTML = new Array();
                                 if (retval.html != '') {
                                     sHTML[sHTML.length] = '<div class="Ilikes">';
                                     sHTML[sHTML.length] = (retval.html) ? retval.html : '';
                                     sHTML[sHTML.length] = '</div>';
                                 }

                                 $lnk.parent().parent().find('.IlikesCont').html(sHTML.join(''));

                             }, function (retval) {
                                 hollandgroen.LoaderHide();
                             }
        ); // EO hollandgroen.Getdata

        pName = null;
        pCat = null;
    };

    // mnu container
    this.SetIlike = function (lnk) {

        hollandgroen.LoaderShow();

        // click hyperlinktag
        var $lnk = $(lnk);
        if ($lnk.length > 0) {
            var valtype = $lnk.attr('valuetype');
            var val = $lnk.attr('value');
            switch (valtype) {
                case 'pic':
                    this.SetPic(val, $lnk);
                    break;
                case 'blog':
                    this.SetBlog(val, $lnk);
                    break;
                default:
                    break;
            };
        };
    }

}

// ------------------------------------------------------------------------------------
// MetaTagClass
// Bij aanmaken van webpagina worden de metatags hiermee gecontroleerd.
// ------------------------------------------------------------------------------------
function SecureMenuClass() {
    //baseclass to use in different scopes
    var BClass = this;
    this.IsLoaded = false;

    // mnu container
    this.$AdminMnu = false;

    this.Init = function () {

        this.$AdminMnu = $('#AdminMnu');
        this.$AdminMnu.find('.MnuItem').hover(
            function () {
                var $p = $(this);
                $p.find('.MnuItemA').css('background-color', '#F2EEE3');
                var $o = $(this).find('.SubMnu');
                if ($o.css('left') == "auto") {
                    $o.position({
                        of: $p,
                        my: "right top",
                        at: "right bottom"
                    })
                    .slideToggle('fast');
                } else {
                    $o.slideToggle('fast');
                };
                $p = null;
                $o = null;
            },
            function () {
                $(this).find('.SubMnu').hide();
                $(this).find('.MnuItemA')
                       .css('background-color', '');
            }
        );

    }

} // EO SecureMenuClass
// ------------------------------------------------------------------------------------

// ------------------------------------------------------------------------------------
// MetaTagClass
// Bij aanmaken van webpagina worden de metatags hiermee gecontroleerd.
// ------------------------------------------------------------------------------------
function MetaTagClass() {

    var that = this;

    // Public Proberties
    // -----------------
    this.mTitle = {
        $inp: $([]),
        maxChar: null,
        $total: $([])
    };  // oMetaTitle

    this.mDesc = {
        $inp: $([]),
        maxChar: null,
        $total: $([])
    };  // oMetaDesc

    this.mKeywords = {
        $inp: $([]),
        maxChar: null,
        $total: $([]),
        $totalTags: $([])
    };  // oMetaKeys

    // Public functions
    // ------------------------------------------------------------------------------------
    this.Init = function () {
        this.TitleValidate();
        this.DescValidate();
        this.KeywordsValidate();

        this.mTitle.$inp.keyup(function () {
            that.TitleValidate();
        });
        this.mDesc.$inp.keyup(function () {
            that.DescValidate();
        });
        this.mKeywords.$inp.keyup(function () {
            that.KeywordsValidate();
        });

    };

    this.TitleValidate = function () {

        if (this.mTitle.$inp.val() != '') {
            var s = this.mTitle.$inp.val().length;
            if (this.mTitle.maxChar < this.mTitle.$inp.val().length) {
                s = '<font color="red">' + s + '</font>';
            }
            this.mTitle.$total.html(s);
            s = null;
        }

    };

    this.DescValidate = function () {

        if (this.mDesc.$inp.val() != '') {
            var s = this.mDesc.$inp.val().length;
            if (this.mDesc.maxChar < this.mDesc.$inp.val().length) {
                s = '<font color="red">' + s + '</font>';
            }
            this.mDesc.$total.html(s);
            s = null;
        }
    };

    this.KeywordsValidate = function () {

        if (this.mKeywords.$inp.val() != '') {
            this.mKeywords.$totalTags.html(this.mKeywords.$inp.val().split(',').length);
            var s = this.mKeywords.$inp.val().length;
            if (this.mKeywords.maxChar < this.mDesc.$inp.val().length) {
                s = '<font color="red">' + s + '</font>';
            }
            this.mKeywords.$total.html(s);
            s = null;
        }
    };

}; // EOF MetaTagClass


// ------------------------------------------------------------------------------------
// 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 sHtml = new Array();
    sHtml.push('<span class="pagerinfo">' + this.Totalrows + ' foto\'s - Pagina ' + this.CurrentPage + ' van ' + this.TotalPages + '</span> ');

    for (var p = pFirst; p <= pLast; p++) {
        if (p == this.CurrentPage) {
            sHtml.push('<span class="pageselect">' + p + '</span>');
        } else {
            sHtml.push('<a href="" class="page" onclick="' + baseclsname + '.GetPageIndex(' + p + '); return false;">' + p + '</a>&nbsp;');
        };
        if (p == pLast && p < this.TotalPages) {
            sHtml.push('<span class="pagertxt">...</span>&nbsp;');
        };
    };

    return sHtml.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
// ------------------------------------------------------------------------------------

var oMnu = new SecureMenuClass();
var obtnILike = new ButtonILikeClass();

$(document).ready(function () {
    oMnu.Init();

    $('.btnIlike').click(
        function () {
            obtnILike.SetIlike(this);
            return false;
        }
    );

    $('.gl_s_Ilike').click(
        function () {

            var $me = $(this);

            // Get Comment formdata
            var senddata = new Object();
            senddata["id"] = $me.attr('value');

            // get data by ajax
            hollandgroen.Getdata('/Fotos/SetILikeForPic'
                             , senddata
                             , function (retval) {
                                 // hide loader div
                                 hollandgroen.LoaderHide();
                                 // update amount
                                 $me.next('.gl_total_ilikes').html(' ' + retval.TotalVotes);
                             }, function (retval) {
                                 hollandgroen.LoaderHide();
                             });
            // EO hollandgroen.Getdata
        }
   );

    $('.gl_s_Public').click(
        function () {

            var $me = $(this);

            // Get Comment formdata
            var senddata = new Object();
            senddata["id"] = $me.attr('value');

            // get data by ajax
            hollandgroen.Getdata('/SecFotos/SetPublic'
                             , senddata
                             , function (retval) {
                                 // hide loader div
                                 hollandgroen.LoaderHide();
                                 // update amount
                                 if (retval.IsVisible) {
                                     $me.attr('src', '/Content/images/mini/public.gif');
                                 } else {
                                     $me.attr('src', '/Content/images/mini/public-no.gif');
                                 }

                             }, function (retval) {
                                 hollandgroen.LoaderHide();
                             });
            // EO hollandgroen.Getdata
        }
   );

    $('.gl_s_SelectPic').click(
        function () {

            var $me = $(this);

            // Get Comment formdata
            var senddata = new Object();
            senddata["id"] = $me.attr('value');

            // get data by ajax
            hollandgroen.Getdata('/SecFotos/SetPicSelected'
                             , senddata
                             , function (retval) {
                                 // hide loader div
                                 hollandgroen.LoaderHide();
                                 // update amount
                                 if (retval.IsSelected) {
                                     $me.attr('src', '/Content/images/mini/lock.gif');
                                 } else {
                                     $me.attr('src', '/Content/images/mini/lock-not.gif');
                                 }

                             }, function (retval) {
                                 hollandgroen.LoaderHide();
                             });
            // EO hollandgroen.Getdata
        }
   );


});
