﻿/// <summary>
/// After a fully load, the window will be resized
/// </summary>
$(window).load(function () {
    resizeWindow();
});

//Default Title
var defaultTitle = "WV de IJsselstreek"

//Trackingcode Google
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1857551-3']);
_gaq.push(['_trackPageview']);

(function () {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

/// <summary>
/// Document Ready
/// </summary>
$(function () {
    init();

    loadMenu();
});

/// <summary>
/// Initialize function
/// </summary>
function init() {
    loadLinkItem();
    loadTweets();
    loadPager();
    initForm();
    loadMemberTable();
    loadTableSorter();
    loadDatePicker();

    $("a.modal").click(function () {
        $.fn.modal({ iframe: true, url: $(this).attr("href"), title: $(this).text() });
        return false;
    });

    //Click function for the Links in the Years Div
    $("div#years a").click(function () {
        loadPage($(this).attr("href"), false);

        return false;
    });

    $("ul#breadcrumb a").click(function () {
//        loadPage($(this).attr("href"), false);

//        return false;
    });

    $("a[rel^='lightbox']").slimbox(null, null, function (el) {
        return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
    });

    //Resize functionality
    $(window).resize(resizeWindow);

    $("div#left").ajaxComplete(function () {
        resizeWindow();
    });

    resizeWindow();
}

/// <summary>
/// Function to add the functionality to Menu
/// </summary>
function loadMenu() {
    $('div#menu a[target!="_blank"]').click(function () {
        var $this = $(this);
        var parent = $this.parents("ul:first");

        parent.find("a").removeClass("active");
        $this.addClass("active");

        return $this.linkClick();
    });
}

/// <summary>
/// Function to add the functionality to LinkItems
/// </summary>
function loadLinkItem() {
    $("div.linkitem").click(function () {
        return $(this).find("a:first").linkClick();
    }).addHover();
}

/// <summary>
/// Function to load the Pager
/// </summary>
function loadPager() {
    $("div.pager").each(function () {
        var $this = $(this);
        var pageSize = parseInt($this.attr("pageSize"));
        var pageIndex = parseInt($this.attr("pageIndex"));
        var totals = parseInt($this.attr("totals"));

        if (!isNaN(pageSize) && !isNaN(pageIndex) && !isNaN(totals)) {
            $this.pager({ Display: pageSize, PageCount: totals, currentPage: pageIndex, onClickFunction: $this.attr("id"), extraProperty: $this.attr("year") });
        }
    });
}

/// <summary>
/// Function to For the NewsPager
/// </summary>
function newsPager(index, year) {
    loadPage("/Nieuws?p=" + index + "&jaar=" + year, false);
}

/// <summary>
/// Function to Load a Page and place it's html in the container
/// </summary>
function loadPage(url, loadSubmenu) {
    if (url != "#") {
        showPreloader();

        $("div#left").load(url, function () {
            init();
            resizeWindow();

            var title = $("div#title").text();

            if (title.length > 0) {
                $(document).attr("title", defaultTitle + " - " + title);
            }

            if (loadSubmenu) {
                var submenu = $.get("/Menu?url=" + escape(url), function (data) {
                    if ($(data).hasChildren("li")) {
                        $("div#submenu").html(data);

                        $('div#submenu a[target!="_blank"]').click(function () {
                            $(this).linkClick();
                            return false;
                        });
                    } else {
                        $("div#submenu").html("");
                    }
                });
            }

            hidePreloader();
        });
    }
}

/// <summary>
/// Function to Load the Member Table
/// </summary>
function loadMemberTable() {
    var yearsDiv = $("div#results div#years");

    if (yearsDiv.exists()) {
        var table = $("div#results table.tablesorter");
        var rows = $("div#results table.tablesorter tr");

        table.hide();

        if (rows.exists()) {
            var years = new Array();

            rows.each(function () {


                $(this).find("td:first").each(function () {
                    var date = Date.parse($(this).text());

                    var year = date.getFullYear();
                    AppendToArray(years, year, false);
                });
            });

            if (years.length > 0) {
                years.sort();

                var ul = $("<ul />");

                for (var i = 0; i < years.length; i++) {
                    var li = $("<li />");
                    var a = $("<a />").attr("href", "#").text(years[i]).click(function () {
                        filterResults(table, parseInt($(this).text()));

                        loadTableSorter();
                        
                        return false;
                    });

                    li.append(a);
                    ul.append(li);
                }

                yearsDiv.prepend(ul);

                //Filter the table based on the latest year
                filterResults(table, years[years.length - 1]);

                table.show();
            }
        }
    }
}

/// <summary>
/// Function to add Functionality to the Tables with the class tablesorter
/// </summary>
function loadTableSorter() {
    //Add a TableSorter Widget to add Click and Hover
    $.tablesorter.addWidget({
        id: "clickHover",
        format: function (table) {
            $("tr:visible", table.tBodies[0]).each(function (i) {
                var tr = $(this);

                tr.find("a:first").each(function () {
                    var a = $(this);
                    tr.addHover();
                    tr.addClass("click");


                    tr.click(function () {
                        loadPage(a.attr("href"), true);
                        return false;
                    });
                });
            });
        }
    });

    $("table.tablesorter").tablesorter({ widgets: ["zebra", "clickHover"], dateFormat: "dd-mm-yyyy" });

}

/// <summary>
/// Function to Load the DatePicker
/// </summary>
function loadDatePicker() {
    //Add functionality for a datePicker
    var datePicker = $("input.datepicker");

    if (datePicker.exists()) {
        datePicker.each(function () {
            $(this).DatePicker({
                view: "years",
                format: "d-m-Y",
                locale: {
                    days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
                    daysShort: ["Zon", "Maa", "Din", "Woe", "Don", "Vri", "Zat", "Zon"],
                    daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zon"],
                    months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
                    monthsShort: ["Jan", "Feb", "Maa", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
                    weekMin: 'wk'
                },
                date: $(this).val(),
                current: $(this).val(),
                calendars: 1,
                starts: 1,
                onChange: function (date, dates, element) {
                    if ((new Date($(element).val()) - new Date(date)) != 0) {
                        $(element).val(date);
                        $(element).DatePickerHide();
                    }
                }
            });
        });
    }
}

/// <summary>
/// Function to Filter the Results Table
/// </summary>
function filterResults(table, filterYear) {
    table.find("tr").each(function () {
        var row = $(this);
        row.find("td:first").each(function () {
            var date = Date.parse($(this).text());

            var year = date.getFullYear();

            if (year == filterYear) {
                row.show();
            } else {
                row.hide();
            }
        });
    });

    resizeWindow();
}

/// <summary>
/// Function to Initialize the Forms
/// </summary>
function initForm() {
    $("form#contactForm").validate({
        rules: {
            Name: { required: true },
            Email: { required: true, email: true },
            ZippCode: { required: true, zipcodeNL: true },
            City: { required: true },
            PhoneNumber: { required: true, phoneNL: true },
            Address: { required: true },
            BirthDate: { required: true, dateNL: true },
            Comments: { required: true }
        }
        //        messages: {
        //            Name: { required: "Naam is verplicht." },
        //            Email: { required: "Email is verplicht.", email: "Er is een ongeldig e-mailadres ingevoerd!" },
        //            ZippCode: { required: "Postcode is verplicht." },
        //            City: { required: "Plaats is verplicht." },
        //            PhoneNumber: { required: "Telefoonnummer is verplicht.", regularExpression: "Voer een Nederlands telefoonnumemr in!" },
        //            Address: { required: "Adres is verplicht." },
        //            BirthDate: { required: "Geboortedatum is verplicht." },
        //            Comments: { required: "Vragen / Opmerkingen is verplicht." }
        //        }
    });

    //Submit action for the forms
    var form = $("form");

    form.submit(function () {

        var action = form.attr("action");
        var serialized = form.serialize();

        $.post(action, serialized, function (data) {
            form.hide();
            $("div#text").html(data);

        });

        return false;
    });
}

/// <summary>
/// Function to get the Link click and load the right function
/// </summary>
$.fn.linkClick = function () {
    var $this = $(this);

    if ($this.exists()) {
        //loadPage($this.attr("href"), true);
    }

   // return false;
}

/// <summary>
/// Function to resize the Window
/// </summary>
function resizeWindow() {
    var height = $("body").height() - 105;
    $("#site").height(height);

    var content = $("#content");

    $("iframe").height(height);

    var contentBottom = content.position().top + content.height();

    var bottom = 0;
    content.find("div").each(function () {
        var $this = $(this);
        var b = $this.position().top + $this.height();

        if (b > bottom) {
            bottom = b;
        }
    });

    if (bottom > contentBottom) {
        var height = (bottom - contentBottom) + content.height();
        content.height(height + 30);
    }
}

/// <summary>
/// Function to Show the PreLoader
/// </summary>
function showPreloader() {
    if (!($("div#ajaxpreloader").exists())) {
        var preloader = $("<div />").attr("id", "ajaxpreloader");
        preloader.append('<img src="/Content/Images/preloader.gif" alt="" />');
        preloader.append("<span>Bezig met laden......</span>");

        $("div#container").append('<div id="modaloverLay">&nbsp;</div>');
        $("div#modaloverLay").height($("div#content").height());
        $("div#container").append(preloader);
        $("div#ajaxpreloader").center();
    } else {
        $("div#ajaxpreloader").show();
        $("div#modaloverLay").height($("div#content").height());
        $("div#modaloverLay").show();
    }
}

/// <summary>
/// Function to Hide the PreLoader
/// </summary>
function hidePreloader() {
    $("div#modaloverLay").hide();
    $("div#ajaxpreloader").hide();
}

/// <summary>
/// Function to Load the latest tweets
/// </summary>
function loadTweets() {
    var twitter = $("#twitter");

    if (twitter.exists()) {
        $.include("/Scripts/jquery/jquery.twitter.js", function () {
            twitter.tweet();
        });
    }
}
