﻿
tpg = function () {

    // Private methods

    //replace @@LocalTime tag with localtime
    function replaceLocalTimeTag(link) {
        var href = link.attr('href');
        href = replaceLocalTimeStr(href);
        link.attr('href', href);
    }

    function replaceLocalTimeStr(str) {
        var now = new Date();
        str = str.replace(/\%40/gi, "@");
        str = str.replace(/@@LocalTime/gi, encodeURIComponent(dateToISOUTC(now)));

        return str;
    }

    // Date functions taken from http://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc
    function dateToUTCArray(date) {
        return [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];
    }

    function dateToArray(date) {
        return [date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()];
    }

    function dateToISO(date) {
        var tem, A = dateToArray(date), i = 0;
        A[1] += 1;
        while (i++ < 7) {
            tem = A[i];
            if (tem < 10) A[i] = '0' + tem;
        }
        return A.splice(0, 3).join('-') + 'T' + A.join(':');
    }

    function dateToISOUTC(date) {
        var tem, A = dateToUTCArray(date), i = 0;
        A[1] += 1;
        while (i++ < 7) {
            tem = A[i];
            if (tem < 10) A[i] = '0' + tem;
        }
        return A.splice(0, 3).join('-') + 'T' + A.join(':');
    }

    function dateJustDate(date) {
        var tem, A = dateToArray(date), i = 0;
        A[1] += 1;
        while (i++ < 7) {
            tem = A[i];
            if (tem < 10) A[i] = '0' + tem;
        }
        return A.splice(0, 3).join('-');
    }

    function escapeHTMLEncode(str) {
        var div = document.createElement('div');
        var text = document.createTextNode(str);
        div.appendChild(text);
        return div.innerHTML;
    }

    function setupLocalTimeLinks() {
        //localTime CSS
        $('a.local-time').bind('click', function () {
            replaceLocalTimeTag($(this));
        });
    }


    function showAsBubble(elementToFloatBy, bubblePos, elementPos, bubbleContents, style) {
        var left = $(elementToFloatBy).removeData('qtip').qtip({
            content: {
                text: bubbleContents
            },
            position: {
                my: bubblePos, // Use the corner...
                at: elementPos // ...and opposite corner
            },
            show: {
                event: false, // Don't specify a show event...
                ready: true // ... but show the tooltip when ready
            },
            hide: {
                event: 'unfocus'
            },
            style: {
                classes: 'ui-tooltip-shadow ui-tooltip-' + style
            }
        });
    }

    function showErrorBubble(elementToFloatBy, bubblePos, elementPos, bubbleContents) {
        showAsBubble(elementToFloatBy, bubblePos, elementPos, bubbleContents, 'red');
    }

    // Leave message blank if using validation summary
    function showValidationError(form, message) {

        var container = $(form).find("[data-valmsg-summary=true]");

        var bubbleTarget = $("[data-valmsg-bubble-target=true]", form);

        // Use the form if no bubble target is found
        if (!bubbleTarget || $(bubbleTarget).length == 0)
            bubbleTarget = form;

        if (!message)
            message = $(container).html();

        // Show client side errors as bubble 
        tpg.showAsBubble(bubbleTarget, $(container).attr("data-valmsg-bubble-pos"), $(container).attr("data-valmsg-element-pos"), message, 'red');
    }

    function formatErrorsForQtip(errors) {
        if (!errors) {
            return "";
        }

        var html = '<ul>';
        var i = 0;
        for (i = 0; i < errors.length; i++) {
            html += '<li>' + errors[i] + '</li>';
        }

        html += '</ul>';

        return html;
    }

    /***** Model Dialog *****/

    //0 means disabled; 1 means enabled;
    var dialogStatus = 0;

    function loadDialog(html, width, headerClass, headerTitle, padding) {

        if (width == undefined) {
            width = 400;
        }

        if (padding == undefined) {
            padding = 8;
        }

        //loads popup only if it is disabled
        if (dialogStatus == 0) {

            var headerTitleHtml = headerClass == "" ? '' : '<h1 class="model-dialog-' + headerClass + ' png" title=' + headerTitle + '></h1>';

            var $dialogHtml = $('<div id="modal-dialog"><div id="center-point"><div id="dialog" style="width:' + width + 'px;">' + headerTitleHtml + '<div id="dialog-content" style="padding:' + padding + 'px" ></div></div></div><div id="modal-dialog-background" onclick="tpg.closeDialog();"></div></div>');

            $('#dialog', $dialogHtml).hide();
            $('#modal-dialog-background', $dialogHtml).hide();

            // fix the background height
            var htmlHeight = $("html").height();
            $("#modal-dialog-background", $dialogHtml).height(htmlHeight);

            $('body').append($dialogHtml);

            $('#dialog-content').html(html);
            $('#dialog-content .dialog-close').click(function () {
                closeDialog();
            });
            $("#dialog").fadeIn("slow");

            $("#modal-dialog-background").css({ "opacity": "0.7" });
            $("#modal-dialog-background").fadeIn("slow");
            dialogStatus = 1;

            //escape event listener
            $(document).keypress(function (e) {
                if (e.keyCode == 27 && dialogStatus == 1) {
                    closeDialog();
                }
            });

            //re-center when images have loaded
            $("#modal-dialog img").load(function () { centerDialog(); })

            centerDialog();
        }
    }

    function closeDialog() {

        if (dialogStatus == 1) {
            $("#modal-dialog").fadeOut("slow", function () {
                $("#modal-dialog").detach();
            });
            dialogStatus = 0;

            $(document).keypress();
        }
    }


    var currentPopup = null;

    function nonModelPopup() {

        $(".pop-container").hover(function () {
        }, function () {
            if (currentPopup != null) {
                currentPopup.animate({ opacity: "hide" }, "fast");
                currentPopup = null;
            }
        });

        $(".popup-trigger").hover(function () {

            var id = $(this).attr("id").replace("pop_trig", "pop_cont");
            var popup = $('#' + id);

            if (currentPopup != null && currentPopup.attr("id") == popup.attr("id")) {
                return;
            }

            if (currentPopup != null && currentPopup.attr("id") != popup.attr("id")) {
                currentPopup.animate({ opacity: "hide" }, "fast");
            }

            var pos = $(this).position();

            popup.css('left', pos.left + 70);
            popup.css('top', pos.top);

            popup.stop(true, true).animate({ opacity: "show" }, "slow");

            currentPopup = popup;

        });
    }

    function comfimationDialog(message, onOk) {
        var html = '<div class="comfirmation-dialog"><p>' + escapeHTMLEncode(message) + '</p><div class="buttons"><input type="button" class="ok-button" value="OK"/><input type="button" class="cancel-button" value="CANCEL"/></div></div>';
        loadDialog(html);

        $('.comfirmation-dialog .ok-button').click(function () { onOk(); closeDialog(); });
        $('.comfirmation-dialog .cancel-button').click(closeDialog);
    }

    function centerDialog() {

        //only need force for IE6
        if ($.browser.msie && parseInt($.browser.version) == 6) {

            var windowWidth = $(window).width();
            var windowHeight = $(window).height();

            $("#modal-dialog").css({
                "height": windowHeight,
                "width": windowWidth
            });

            $("#modal-dialog-background").css({
                "height": windowHeight,
                "width": windowWidth
            });
        }

        var width = $("#dialog").width();
        var height = $("#dialog").height();

        //centring, slightly above centre
        $("#dialog").css({
            "margin-left": (width / 2) * -1,
            "margin-top": ((height / 2) * -1 ) - 50
        });
    }

    return {
        dateToISO: dateToISO,
        dateToISOUTC: dateToISOUTC,
        dateJustDate: dateJustDate,
        dateToUTCArray: dateToUTCArray,
        escapeHTMLEncode: escapeHTMLEncode,
        nonModelPopup: nonModelPopup,
        setupLocalTimeLinks: setupLocalTimeLinks,
        showAsBubble: showAsBubble,
        showErrorBubble: showErrorBubble,
        showValidationError: showValidationError,
        formatErrorsForQtip: formatErrorsForQtip,
        loadDialog: loadDialog,
        closeDialog: closeDialog,
        comfimationDialog: comfimationDialog,
        centerDialog: centerDialog
    }

} ();

