﻿/// <summary>
/// jquery Function for binding the AjaxUpload to an element
/// </summary>
$.fn.ajaxUpload = function () {
    if ($(this).exists()) {
        $(this).each(function () {
            var descriptionField = $(this).parent().first().find("div.uploadDescription");
            var link = $(this);
            var filePath = "";
            new AjaxUpload(link, {
                action: "/FileUploadHandler.ashx",
                onSubmit: function (file, ext) {

                    if (ext.toLowerCase() && /^(css|jpg|png|jpeg|gif|bmp|avi|wmv|mp4|mpeg|mpg|mp3|wma|wav|doc|docx|rtf|xls|xlsx|pdf|ppt|pptx|vsd|swf|zip|epub|)$/.test(ext.toLowerCase())) {
                        descriptionField.text("Bezig met uploaden....");
                    } else {
                        // extension is not allowed
                        descriptionField.text("De gekozen extensie kan niet geupload worden!");
                        // cancel upload
                        return false;
                    }

                    if (this._input != null && this._input.value != "") {
                        filePath = this._input.value;
                    }
                },
                onComplete: function (file, response) {
                    var urlField = $("#" + link.attr("assetclientid"));
                    var descriptionUrlField = $("#" + link.attr("asseturldescriptionclientid"));

                    descriptionField.text("Uploaden van file " + file + " : " + response);

                    if (response.startsWith("De volgende fout is opgetreden:")) {
                        descriptionField.show();
                        descriptionField.text(response);
                    }
                    else if (response.startsWith("Het volgende bestand bestaat al:")) {
                        if (confirm(response + "\n Wilt u dit bestand overschrijven?")) {
                            this.setData({ "overwriteFile": true });
                            this.submit(filePath);
                        }
                    } else {
                        urlField.val(response)
                        //descriptionUrlField.val(file.replace(".docx", ".pdf").replace(".doc", ".pdf"));

                        urlField.change();
                        descriptionField.hide();
                    }
                }
            });
        });
    }
}

/// <summary>
/// jquery function add a Zebra element to a container
/// </summary>
$.fn.zebra = function () {
    var zebra = $(this);

    zebra.children(":not(.header)")
        .filter(":even").removeClass("odd").addClass("even").end()
        .filter(":odd").removeClass("even").addClass("odd").end()
        .addHover();
}

/// <summary>
/// jquery function to check if an element exists
/// </summary>
$.fn.exists = function () {
    return ($(this).length > 0);
}

/// <summary>
/// jquery function to check if a string Startswith the given text
/// </summary>
$.fn.startsWith = function (text) {
    if (this != null && text != null) {
        return (text.toLowerCase() == this.substring(0, text.length).toLowerCase());
    }

    return false;
}

/// <summary>
/// Format a string (like the .net string.Format function)
/// </summary>
jQuery.format = function jQuery_dotnet_string_format(text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; ++token) {
        //iterate through the tokens and replace their placeholders from the text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }

    return text;
};

/// <summary>
/// Hover of an element
/// </summary>
$.fn.addHover = function () {
    $(this).hover(function () {
        $(this).addClass("hover");
    }, function () {
        $(this).removeClass("hover");
    });

    return this;
}

/// <summary>
/// Check the links for documents, to place them in a modal Dialog
/// </summary>
$.fn.checkDocument = function (layout) {
    $(this).each(function () {
        var a = $(this);

        a.bind("click", function () {
            var documentUrl = a.attr("href");

            if (documentUrl) {
                if (documentUrl.indexOf("javascript:TestURL('") == 0) {
                    var id = documentUrl.substring(documentUrl.indexOf("\'") + 1, documentUrl.lastIndexOf("\'"));

                    documentUrl = $("#" + id).val();
                }

                var ext = getExtension(documentUrl);

                //Only show Documents for a given Extension in a popup
                if (ext.toLowerCase() && /^(jpg|png|jpeg|gif|bmp|avi|wmv|mp4|mpeg|mpg|mp3|wav|pdf|)$/.test(ext.toLowerCase())) {
                    var objectData = null;
                    var documentTitle = a.text();
                    var objectData = null;
                    var objectType = null;
                    var objectWidth = 0;
                    var objectHeight = 0;
                    var showInParent = false;

                    //Define the Default height / width
                    if (layout) {
                        objectWidth = layout.state.container.innerWidth - 100;
                        objectHeight = layout.state.container.innerHeight - 100;
                    } else {
                        if ($(parent).exists()) {
                            showInParent = true;
                            objectWidth = $(parent).width() - 100;
                            objectHeight = $(parent).height() - 100;
                        } else {
                            objectWidth = $(document).width() - 100;
                            objectHeight = $(document).height() - 100;
                        }
                    }

                    //check for images
                    if (ext.toLowerCase() && /^(jpg|png|jpeg|gif|bmp|)$/.test(ext.toLowerCase())) {
                        objectData = $.format('<img src="{0}" alt="{1}" />', documentUrl, documentTitle);
                    } else if (ext.toLowerCase() && /^(avi|wmv|mp4|mpeg|mpg|mp3|wav|)$/.test(ext.toLowerCase())) {
                        //Video's
                        switch (ext) {
                            case "mpeg":
                            case "mpg":
                                objectWidth = 400;
                                objectHeight = 300;
                                objectType = "video/mpeg";
                                break;

                            case "avi":
                                objectWidth = 400;
                                objectHeight = 300;
                                objectType = "video/x-msvideo";
                                break;

                            case "wmv":
                                objectWidth = 400;
                                objectHeight = 300;
                                objectType = "video/x-ms-wmv";
                                break;

                            case "wav":
                                objectWidth = 200;
                                objectHeight = 20;
                                objectType = "audio/x-wav";
                                break;

                            case "mp3":
                                objectWidth = 200;
                                objectHeight = 20;
                                objectType = "audio/mpeg";

                                break;
                        }

                        objectData = $.format('<object data="{0}" type="{1}" width="{2}" height="{3}"><param name="src" value="{0}"><param name="autoplay" value="true"><param name="autoStart" value="1">Het document kan niet geopend worden. Klik op de volgende link om het opnieuw te proberen: <a href="{0}">{4}</a></object>', documentUrl, objectType, objectWidth, objectHeight, documentTitle);

                    } else {
                        //Documents
                        switch (ext) {
                            case "doc":
                            case "docx":
                                objectType = "application/msword";
                                break;

                            case "xls":
                            case "xlsx":
                                objectType = "application/vnd.ms-excel";
                                break;

                            case "pdf":
                                objectType = "application/pdf";
                                break;

                            case "ppt":
                            case "pptx":
                                objectType = "application/vnd.ms-powerpoint";
                                break;

                            case "vsd":
                                objectType = "application/vnd.ms-visio";
                                break;
                        }

                        //For SharePoint, change receive options
                        //if (documentUrl.indexOf(getDomain()) == 0 || documentUrl.indexOf("/") == 0) {
                        objectData = $.format('<object data="{0}" type="{1}" width="{2}"  height="{3}">Het document kan niet geopend worden. Klik op de volgende link om het opnieuw te proberen: <a href="{0}">{4}</a></object>', documentUrl, objectType, objectWidth, objectHeight, documentTitle);
                        //} else {
                        //    objectData = $.format('<iframe src="{0}" marginheight="0" marginwidth="0" width="{1}" height="{2}"></iframe>', documentUrl, objectWidth, objectHeight);
                        //}
                    }

                    //If there is objectData, override the onclick
                    if (objectData != null) {

                        var div = $("<div />").append(objectData);
                        div.infoPuntModal({ parent: true, title: documentTitle, width: objectWidth, height: objectHeight });

                        return false;
                    }
                }
            }
        });
    });
}

/// <summary>
/// Modal for the InfoPunt
/// </summary>
$.fn.infoPuntModal = function (options) {
    var element = $(this);
    var body = $("body");
    this.options = $.extend({
        center: true,
        parent: false,
        title: "Infopunt modal dialog",
        width: 400,
        height: 300,
        iframe: false,
        url: ""
    }, options);

    var modal = $("#modaldialog");

    //Get the parent, if it is given
    if (this.options.parent && $(parent).exists() && parent.$("#modaldialog").exists()) {
        modal = parent.$("div#modaldialog");
        body = parent.$("body");
    }

    if (modal.exists()) {
        modal.empty();

        var modalOverlay = $('<div id="modaloverLay" />').html("&nbsp;");

        modalOverlay.height($(document).height());
        //close of the Modal
        modalOverlay.click(function () {
            container.fadeOut();
            modal.hide();

            modalOverlay.hide();
        });

        //Add the Overlay
        modal.prepend(modalOverlay);

        var container = $("<div />").attr("id", "container");
        var header = $("<div />").attr("id", "header");
        $("<div />").attr("class", "title").html(this.options.title).appendTo(header);
        var close = $("<div />").attr("class", "close");

        //Add the Close functionality
        close.click(function () {
            modal.hide();

            modalOverlay.hide();
        });

        header.append(close);

        //Add functionality to a closebutton if it is present
        var closeButton = element.find("#closebutton");
        if (closeButton.exists()) {
            closeButton.click(function () {
                modal.hide();

                modalOverlay.hide();
            });
        }

        container.append(header);

        var showImage = false;

        //If it is an Iframe dialog, add the url to the Iframe
        if (this.options.iframe) {
            var iframe = $("<iframe />");
            iframe.attr("frameborder", "0").width(this.options.width).height(this.options.height);

            if (this.options.url.length > 0) {
                iframe.attr("src", this.options.url);
                iframe.load(function () {
                    var workspace = iframe.contents().find("#s4-workspace");
                    if (workspace.height() > $(this).height()) {
                        workspace.height($(this).height());
                    }
                });
            } else {
                iframe.append(element);
            }

            container.append(iframe);

        } else {
            var img = element.find("img:first-child");

            if (img.exists()) {
                showImage = true;
                var image = new Image();
                image.src = img.attr("src");

                $(image).ready(function () {
                    var resize = false;
                    if (image.width > options.width || image.height > options.height) {
                        resize = true;
                    } else if (image.width < options.width || image.height < options.height) {
                        options.width = image.width;
                        options.height = image.height;

                        resize = true;
                    }

                    if (resize) {
                        img = img.resize({ width: options.width, height: options.height });
                    }
                });
            }

            container.append(element);
        }

        container.fadeIn().width(this.options.width + 2).height(this.options.height + 32);
        modal.append(container);

        if (this.options.center) {
            container.center({ width: this.options.width, height: this.options.height + 30, inside: this.options.parent ? parent.window : window });
        }

        modal.show();

        return modal;
    }
}

$.fn.modalContainer = function (options) {
    $(this).fadeIn().width(options.width + 2).height(options.height + 32);

    if (options.center) {
        $(this).center({ width: options.width, height: options.height + 30, inside: options.parent ? parent.window : window });
    }
}

/// <summary>
/// Twitter control for InfoPunt
/// </summary>
$.fn.twitter = function (options) {
    var control = $(this);

    if (control.exists()) {
        var options = $.extend({ // Default values
            user: "infopunt",
            count: 5,
            header: "Laatste tweets",
            slideIn: true,
            slideDuration: 750,
            showHeader: true
        }, options);

        //Get the ItemCount from the Control if applied
        if (parseInt(control.attr("items"))) {
            options.count = parseInt(control.attr("items"));
        }

        control.hide();

        try {
            $.getJSON("http://twitter.com/statuses/user_timeline/" + options.user + ".json?count=" + options.count, function (data) {
                if (options.showHeader) {
                    var header = $("<div />").addClass("header").html('<a href="http://twitter.com/' + options.user + '">' + options.header + '</a>');
                    control.append(header);
                }
                var ul = $("<ul />");
                $.each(data, function () {
                    var item = $("<li />");

                    var username = this.user.screen_name;
                    var status = this.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function (url) {
                        return '<a href="' + url + '">' + url + '</a>';
                    }).replace(/\B@([_a-z0-9]+)/ig, function (reply) {
                        return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
                    });

                    //item.append('<span>' + status + '</span> <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + this.id + '">' + relative_time(this.created_at) + '</a></li>');

                    item.append("<span>" + status + "</span>"); //<a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + this.id + '">' + relative_time(this.created_at) + '</a>');
                    //item.append("</li>");
                    ul.append(item);
                });

                if (control.hasClass("zebra")) {
                    ul.zebra();
                }

                control.append(ul);

                // show twitter list
                if (options.slideIn) {
                    control.show().animate(options.slideDuration);
                }
                else {
                    control.show();
                }

                if (typeof (resizeContent) == "function") {
                    resizeContent();
                }
            });
        } catch (e) {
        }
    }
}

$.fn.fixUrl = function (elementName) {
    $(this).find(elementName).each(function () {

        var text = $(this).html();

        var status = text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function (url) {
            return '<a href="' + url + '">' + url + '</a>';
        });

        $(this).html(status);
    });
}

$.fn.textResizer = function () {
    var $this = $(this);

    if (!$this.exists()) {
        $this = $("html");
    }

    // Reset Font Size
    var originalFontSize = $this.css("font-size");

    $this.applyOriginalLineHeight();

    $(".resetfont").click(function () {
        $this.resizeFontSize(1, originalFontSize);

        return false;
    });

    // Increase Font Size
    $(".increasefont").click(function () {
        $this.resizeFontSize(1.2);

        return false;
    });
    // Decrease Font Size
    $(".decreasefont").click(function () {
        $this.resizeFontSize(0.8);

        return false;
    });
}

$.fn.resizeFontSize = function (count, original) {
    var $this = $(this);
    var currentFontSize = $this.css("font-size");
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum * count;

    if (count == 1 && original) {
        newFontSize = original;
    }

    $this.css("font-size", newFontSize);

    $this.resizeLineHeight(count);

    if (typeof (resizeContent) == "function") {
        resizeContent();
    }
}

$.fn.applyOriginalLineHeight = function () {
    $(this).children().each(function () {
        var lineHeight = $(this).css("line-height");

        if (lineHeight != "normal") {
            $(this).attr("original-line-height", lineHeight);
        }

        $(this).applyOriginalLineHeight();
    });
}

$.fn.resizeLineHeight = function (count) {
    var $this = $(this);

    if ($this.exists()) {
        var lineHeight = $this.css("line-height");

        if (lineHeight != "normal") {
            var current = parseFloat(lineHeight, 10);
            var newSize = current * count;

            var original = $this.attr("original-line-height");
            if (count == 1 && original) {
                newSize = parseFloat(original, 10);
            }

            $this.css("line-height", $.format("{0}px", newSize));

            if (typeof (resizeContent) == "function") {
                resizeContent();
            }
        }

        $this.children().each(function () {
            $(this).resizeLineHeight(count);
        });
    }
}

/// <summary>
/// Get extension of a file
/// </summary>
function getExtension(fileName) {
    if (fileName.indexOf(".") !== -1) {
        var index = fileName.indexOf("?");
        if (index !== -1) {
            fileName = fileName.substring(0, index);
        }

        index = fileName.lastIndexOf(".") + 1;

        return fileName.substring(index);
    }

    return ""
}

/// <summary>
/// Get the absolute Path of the url
/// </summary>
function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

/// <summary>
/// Get the Domain of the Url
/// </summary>
function getDomain() {
    return $.format("{0}//{1}", window.location.protocol, window.location.host);
}

/// <summary>
/// Functions to Append a value to an Array
/// </summary>
function AppendToArray(array, value, add) {
    var position = jQuery.inArray(value, array);

    if (value.trim().length > 0) {
        //Get or remove the id from the selectedIds
        if (add) {
            if (position == -1) {
                array.push(value);
            }
        } else {
            if (position > -1) {
                array.splice(position, 1);
            }
        }
    }

    return array;
}

function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'less than a minute ago';
    } else if (delta < 120) {
        return 'about a minute ago';
    } else if (delta < (60 * 60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if (delta < (120 * 60)) {
        return 'about an hour ago';
    } else if (delta < (24 * 60 * 60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if (delta < (48 * 60 * 60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
}

/// <summary>
/// jQuery function to Center an element
/// </summary>
(function ($) {
    $.fn.extend({
        center: function (options) {
            var options = $.extend({ // Default values
                inside: window, // element, center into window
                transition: 0, // millisecond, transition time
                minX: 0, // pixel, minimum left element value
                minY: 0, // pixel, minimum top element value
                vertical: true, // booleen, center vertical
                withScrolling: false, // booleen, take care of element inside scrollTop when minX < 0 and window is small or when window is big 
                horizontal: true, // booleen, center horizontal
                vertical: true,
                width: 0,
                height: 0
            }, options);
            return this.each(function () {
                var $this = $(this);
                var props = { position: 'absolute' };
                if (options.vertical) {
                    var top = ($(options.inside).height() - ($this.outerHeight() > 0 ? $this.outerHeight() : options.height)) / 2;
                    if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                    top = (top > options.minY ? top : options.minY);
                    $.extend(props, { top: top + 'px' });
                }
                if (options.horizontal) {
                    var left = ($(options.inside).width() - ($this.outerWidth() > 0 ? $this.outerWidth() : options.width)) / 2;
                    if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                    left = (left > options.minX ? left : options.minX);
                    $.extend(props, { left: left + 'px' });
                }
                if (options.transition > 0) $this.animate(props, options.transition);
                else $this.css(props);

                return $this;
            });
        }
    });
})(jQuery);

(function ($) {
    $.fn.resize = function (options) {

        var self = $(this)
		, mathFloor = Math.floor
		, browser = $.browser
		, isIE6 = browser.msie && (parseInt(browser.version) == 6)
		, aspectRatio = 0
		, params = $.extend({
		    height: 0,
		    width: 0
		}, options)
		;

        // We cannot do much unless we have one of these

        if (!params.height && !params.width) {
            return self;
        }

        // Calculate aspect ratio now, if possible
        if (params.height && params.width) {
            aspectRatio = params.width / params.height;
        }

        // Attach handler to load
        // Handler is executed just once per element
        // Load event required for Webkit browsers
        return self.one("load", function () {

            // Remove all attributes and CSS rules
            $(this).removeAttr("height")
					 .removeAttr("width")
					 .css({
					     height: "",
					     width: ""
					 });

            var imgHeight = this.height
			, imgWidth = this.width
			, imgAspectRatio = imgWidth / imgHeight
			, bxHeight = params.height
			, bxWidth = params.width
			, bxAspectRatio = aspectRatio;

            // Work the magic!
            // If one parameter is missing, we just force calculate it
            if (!bxAspectRatio) {
                if (bxHeight === 0) {
                    bxAspectRatio = imgAspectRatio - 1;
                } else {
                    bxAspectRatio = imgAspectRatio + 1;
                }
            }

            // Only resize the images that need resizing
            if ((bxHeight && imgHeight > bxHeight) || (bxWidth && imgWidth > bxWidth)) {

                if (imgAspectRatio > aspectRatio) {
                    bxHeight = mathFloor(imgHeight / imgWidth * bxWidth);
                } else {
                    bxWidth = mathFloor(imgWidth / imgHeight * bxHeight);
                }

                $(this).attr({
                    "height": bxHeight,
                    "width": bxWidth
                });
            }
        })
		.each(function () {

		    // Trigger load event (for Gecko and MSIE)
		    if (this.complete || isIE6) {
		        $(this).trigger("load");
		    }
		});
    };
})(jQuery);

/**
* A simple querystring parser.
* Example usage: var q = $.parseQuery(); q.fooreturns  "bar" if query contains "?foo=bar"; multiple values are added to an array. 
* Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object .
* http://actingthemaggot.com/jquery
*
* Copyright (c) 2008 Michael Manning (http://actingthemaggot.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
**/
jQuery.parseQuery = function (qs, options) {
    var q = (typeof qs === 'string' ? qs : window.location.search), o = { 'f': function (v) { return unescape(v).replace(/\+/g, ' '); } }, options = (typeof qs === 'object' && typeof options === 'undefined') ? qs : options, o = jQuery.extend({}, o, options), params = {};
    jQuery.each(q.match(/^\??(.*)$/)[1].split('&'), function (i, p) {
        p = p.split('=');
        p[1] = o.f(p[1]);
        params[p[0]] = params[p[0]] ? ((params[p[0]] instanceof Array) ? (params[p[0]].push(p[1]), params[p[0]]) : [params[p[0]], p[1]]) : p[1];
    });

    return params;
}

$.urlParam = function (url, name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);

    if (!results) {
        return 0;
    }

    return results[1] || 0;
}
