// used to warn the user about possible XSS problems
// don't worry, we're checking on the server as well (using the build-in ASP.NET validate request), but this helps the user experience
$(document).ready(function () {
    $("form").submit(function () {
        var result = true;
        var control;

        $("input").each(function (i, val) {
            var m = mayContainXss($(val).val());
            if (m)
                control = $(val);
            result = result && !m;
        });
        $("textarea").each(function (i, val) {
            var m = mayContainXss($(val).val());
            if (m)
                control = $(val);
            result = result && !m;
        });

        if (!result) {
            control.addClass("epunkt-error").focus();
            $("<div>Please check your input in the marked control and remove special characters like < or >.</div>")
                .dialog({
                    modal: true,
                    autoOpen: true,
                    width: 400,
                    resizable: false,
                    buttons: {
                        "OK": function () {
                            $(this).dialog("close").dialog("destroy");
                        }
                    }
                });
        }

        return result;
    });
});

function mayContainXss(text) {
    var r = new RegExp("<[a-zA-Z]", "i");
    return r.test(text);
}  


function Dialog(control, width, height, okCallback) {
    HideDropDowns();
    $(control)
        .show()
        .dialog({
            modal: true,
            width: width,
            height: height,
            resizable: false,
            close: function() {
                $(this).dialog("destroy");
                ShowDropDowns()
            },
            buttons: {
                "Save": function() {
                    ShowDropDowns();
                    okCallback();
                    $(this).dialog("close");
                }
            }
        });
}

function DialogWithoutButtons(control, width, height) {
    HideDropDowns();
    $(control)
        .show()
        .dialog({
            modal: true,
            width: width,
            height: height,
            resizable: false,
            close: function() {
                $(this).dialog("destroy");
                ShowDropDowns()
            }
        });
}

function Message(message, redirectUrl) {
    HideDropDowns();
    $("<div title='&nbsp;'>" + message + "</div>")
        .appendTo("body")
        .dialog({
            modal: true,
            overlay: {
                opacity: 0.9,
                background: "white"
            },
            width: 770,
            height: 130,
            resizable: false,
            close: function() {
                $(this).dialog("destroy");
                ShowDropDowns()
            },         
            buttons: {
                "Next": function() {
                    $(this).dialog("close");
                    if (redirectUrl)
                        location = redirectUrl;
                }
            }
        });
}

function ConfirmMessage(okCallback) {
    HideDropDowns();
    $("<div title='&nbsp;'>Are you sure you want to proceed?</div>")
        .appendTo("body")
        .dialog({
            modal: true,
            height: 115,
            resizable: false,
            close: function() {
                $(this).dialog("destroy");
                ShowDropDowns()
            },
            buttons: {
                "Yes, proceed": function() {
                    $(this).dialog("close");
                    okCallback();
                },
                "No": function() {
                    $(this).dialog("close");
                }
            }
        });
}

function DatePicker(control) {
    var culture = "en";
    culture = culture == "en" ? "" : culture;
    $.datepicker.setDefaults($.datepicker.regional[culture]);
    
    $(control).datepicker({
        dateFormat: "yy-mm-dd",
        yearRange: "c-100:c+0",
        changeMonth: true,
		changeYear: true
    });

    //this is a fix for the jquery datepicker, because the proper class won't be added otherwise 
    $("#ui-datepicker-div").addClass("ui-datepicker-div");
}

function ReplaceBreaksWithCrlf(text) {
    if (!text)
        return "";
    while (text.indexOf("<br />", 0) >= 0)
        text = text.replace("<br />", "\r\n");
    return text;
}

function HideDropDowns() {
    if ($.browser.msie && $.browser.version < 7)
        $(".hide-dropdown").hide();
}

function ShowDropDowns() {
    if ($.browser.msie && $.browser.version < 7)
        $(".hide-dropdown").show();
}

function MaxLength(textarea, maxLength) {
    var divId = "___MaxLength";

    $(textarea).blur(function() {
        $("#" + divId).remove();
    });
    
    $(textarea).focus(function() {
        var left = $(textarea).offset().left;
        var top = $(textarea).offset().top;        
                
        $("<div>")
            .attr("id", divId)
            .addClass("epunkt-grid-item")
		    .css({
			    position: "absolute",
			    left: left,
			    top: top,
			    width: 150,
			    zIndex: 99999
		    })
		    .hide()
		    .html($(textarea).val().length + "/" + maxLength + " Characters.")
		    .appendTo("body")
		    .show()
		    .css({
		        top: top - $("#" + divId).height()
		    });
    });

    $(textarea).keyup(function() {
        $("#" + divId)
            .html($(textarea).val().length + "/" + maxLength + " Characters.");
    });
    
    $(textarea).keydown(function(evnt) {
        if (evnt.keyCode == 8 || evnt.keyCode == 46 || evnt.keyCode == 37 || evnt.keyCode == 39 || evnt.keyCode == 38 || evnt.keyCode == 40) //we still allow Backspace, Del and the Cursors.
            return true;
        if ($(textarea).val().length >= maxLength)
            return false;
    });    
}


(function($) {
    $.fn.maxLen = function(maxLength) {

        $(this).each(function() {
            var divId = "___maxLength";

            $(this).attr("maxlength", maxLength);

            $(this).blur(function() {
                $("#" + divId).remove();
            });

            $(this).focus(function() {
                var left = $(this).offset().left;
                var top = $(this).offset().top - 14;

                $("<div>")
                    .attr("id", divId)
                    .addClass("epunkt-grid-item")
                    .css({
                            position: "absolute",
                            left: left,
                            top: top,
                            width: 100,
                            zIndex: 99999
                        })
                    .hide()
                    .appendTo("body")
                    .show();

                $(this).keyup();
            });

            $(this).keyup(function() {
                $("#" + divId).html($(this).val().length + "/" + maxLength + " Characters.");
            });
        });
    };
})(jQuery);


(function ($) {
    $.fn.bubble = function(text, width) {
        if (!text)
            text = "nbsp;";
        if (!width)
            width = 200;

        $(this).css("cursor", "help");

        $(this).hover(function() {
            var left = $(this).offset().left;
            var top = $(this).offset().top + 25;

            if (left + 10 + width > $(document).width())
                left = $(document).width() - 10 - width;

            $("#_____bubble").remove();
            $("<div>")
                .attr("id", "_____bubble")
                .addClass("epunkt-hover-box")
                .css({
                        position: "absolute",
                        left: left,
                        top: top,
                        width: width,
                        zIndex: 99999
                    })
                .html(text)
                .hide()
                .appendTo("body")
                .fadeIn(100);
        }, function() {
            $("#_____bubble")
                .fadeOut(100);
        });

        return $(this);
    };
})(jQuery);


(function ($) {
    $.fn.watermark = function(text) {

        var textbox = $(this);

        textbox.blur(function() {
            if (textbox.val() == "")
                textbox.val(text).addClass("epunkt-watermark");
        });

        textbox.click(function() {
            if (textbox.val() == text)
                textbox.val("").removeClass("epunkt-watermark");
        });

        $(document).ready(function() {
            if (textbox.val() == "")
                textbox.val(text).addClass("epunkt-watermark");
        });

        return textbox;
    };
})(jQuery);

(function($) {
    $.fn.autoComplete = function(options) {
        var defaults = {
            seperator: null,
            cssClassItems: "epunkt-autocomplete-items",
            cssClassItem: "epunkt-autocomplete-item",
            cssClassItemHover: "epunkt-autocomplete-item-hover",
            triggerEnterOnClick: false
        };
        options = $.extend(defaults, options);
        if (options.method == null)
            return $(this);

        var cache = null;
        var cacheIsBeeingFilled = false;
        var selectedIndex = -1;
        var lastTextbox = null; //we use these variables or the ajax-callback-method would need a lot more parameters
        var lastText = null;

        function GetId() {
            return "___autoComplete";
        }

        function GetItemId(index) {
            return "___autoComplete_" + index;
        }

        function Remove() {
            $("#" + GetId()).remove();
            selectedIndex = -1;
        }

        function RenderItems(textbox, text) {
            var html = "";

            var filtered = new Array();
            $.each(cache, function(i, tag) {
                if (i <= 20 && tag.toLowerCase().indexOf(text.toLowerCase(), 0) >= 0)
                    filtered.push(tag);
            });

            $.each(filtered, function(i, tag) {
                var highlightedText = tag.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + text.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<b>$1</b>");
                html += "<div title='" + tag + "' class='" + options.cssClassItem + "' id='" + GetItemId(i) + "'>" + highlightedText + "</div>";
            });

            if (html == "")
                Remove();
            else
                $("#" + GetId())
                            .html(html)
                            .css({
                                top: (textbox.offset().top + textbox.height() + 3) + "px",
                                left: (textbox.offset().left) + "px",
                                width: (textbox.width() + 4) + "px"
                            })
                            .show();

            $.each(filtered, function(i, tag) {
                $("#" + GetItemId(i)).click(function(evnt) {
                    AddText(textbox, tag, options.triggerEnterOnClick);
                });
            });
        }

        function AddText(textbox, tag, triggerEnter) {
            var existingText = textbox.val();

            if (options.seperator != null && options.seperator != "" && existingText.lastIndexOf(options.seperator) >= 0)
                existingText = existingText.substring(0, existingText.lastIndexOf(options.seperator)) + options.seperator + " ";
            else
                existingText = "";
            textbox.val(existingText + tag);
            textbox.focus();

            if (triggerEnter)
                textbox.trigger("keyup", [{
                    preventDefault: function() { },
                    keyCode: 13
}]);
        }

        function SelectItem(textbox) {
            $("." + options.cssClassItemHover).removeClass(options.cssClassItemHover);
            var selectedItem = $("#" + GetItemId(selectedIndex));
            selectedItem.addClass(options.cssClassItemHover);
            AddText(textbox, selectedItem.attr("title"), false);
        }

        function SetCache(items) {
            cache = new Array();
            $.each(items, function(i, val) {
                cache.push(val);
            });
            cacheIsBeeingFilled = false;
            RenderItems(lastTextbox, lastText);
        }

        return this.each(function() {
            var textbox = $(this);
            textbox.attr("autocomplete", "off");

            textbox.keydown(function(event) {
                if (event.which == 13 || event.which == 9) { //ENTER, TAB
                    if ($("#" + GetId(selectedIndex)).length > 0) {
                        textbox.val(textbox.val() + options.seperator + " ");
                        setTimeout("$('#" + textbox.attr("id") + "').focus();", 50);
                    }
                    Remove();
                }
            });

            textbox.keyup(function(event) {
                var text = textbox.val();
                if (options.seperator != null && options.seperator != "")
                    if (text.lastIndexOf(options.seperator) >= 0)
                    text = text.substring(text.lastIndexOf(options.seperator) + 1);
                text = $.trim(text);

                if (event.which == 8) //backspace clears the cache
                    cache = null;

                if (text.length > 1) {
                    if ($("#" + GetId()).length <= 0) {
                        $("<div />")
                                    .attr("id", GetId())
                                    .addClass(options.cssClassItems)
                                    .hide()
                                    .css({
                                        top: (textbox.offset().top + textbox.height() + 3) + "px",
                                        left: (textbox.offset().left) + "px",
                                        width: (textbox.width() + 4) + "px",
                                        position: "absolute",
                                        zIndex: 9999
                                    })
                                    .insertAfter(textbox)
                    }


                    $(document).click(function() {
                        Remove();
                    });
                    $(window).resize(function() {
                        $(document).click();
                    });

                    if (event.which == 40 || event.which == 38) {
                        if (event.which == 38) //KEYUP
                            selectedIndex--;
                        else if (event.which == 40) //KEYDOWN
                            selectedIndex++;

                        if (selectedIndex < 0 || $("#" + GetId(selectedIndex)).length <= 0)
                            selectedIndex = 0;

                        SelectItem(textbox);
                    }
                    else if (event.which == 37 || event.wich == 39) { //KEYLEFT, KEYRIGHT
                        //do nothing here
                    }
                    else {
                        if (cache==null && !cacheIsBeeingFilled) {
                            cacheIsBeeingFilled = true;
                            lastTextbox = textbox;
                            lastText = text;
                            var textToSuggestFor = text;
                            while (textToSuggestFor.indexOf("/") >= 0)
                                textToSuggestFor = textToSuggestFor.replace("/", "");
                            options.method(textToSuggestFor, SetCache);
                        }
                        else if (cache)
                            RenderItems(textbox, text);
                    }
                }
                else {
                    Remove();
                }
            });

        });
    }
})(jQuery);
(function ($) {
    $.fn.feedbackDialog = function () {
        var link = $(this);

        var dialog = $("#feedbackDialog");
        var confirmationDialog = $("#feedbackConfirmationDialog");

        var confirmationButtons = {};
        confirmationButtons[confirmationDialog.data("buttontext")] = function () {
            confirmationDialog.dialog("close");
        };

        var buttons = {};
        buttons[dialog.data("buttontext")] = function () {
            var text = dialog.find("#feedback").val();
            var email = dialog.find("#email").val();
            var url = window.location.href;

            dialog.next().hide(); //hide the button

            $.ajax({
                url: dialog.data("posturl"),
                type: "POST",
                data: { url: url, feedback: text, email: email, calledViaJavaScript: true },
                success: function () {
                    dialog.next().show();
                    dialog.dialog("close");
                    confirmationDialog.dialog("open");
                }
            });
        };

        dialog.dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 600,
            buttons: buttons
        });

        confirmationDialog.dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 600,
            buttons: confirmationButtons
        });

        link.attr("href", "javascript:void(0);").click(function () {
            dialog.dialog("open");
        });

        return link;
    };
})(jQuery);
