﻿// this script requires jQuery be loaded in advance

$(document).ready(function () {
    handleDefaults();

    $(".inline-editable").each(function () {
        var label = $(this);
        label.wrap("<span class='inline-edit-wrap' />");

        var parent = $(this).parent();

        label.before("<input type='text' class='inline-editor' value='" + label.text() + "'>");

        var editorWidth = label.attr("width");

        var editor = parent.children("input:first");
        editor.attr("id", label.attr("id"));
        editor.attr("readonly", "true");
        editor.attr("title", "Click to edit");
        editor.css("width", editorWidth);

        if (label.hasClass("required"))
            editor.addClass("required");

        if (label.hasClass("email"))
            editor.addClass("email");

        if (label.hasClass("number"))
            editor.addClass("number");

        editor.mouseenter(function() {DoMouseEnter(editor);});
        editor.mouseleave(function() {DoMouseLeave(editor);});
        editor.blur(function() {RemoveEditable(editor);});
        editor.click(function () {MakeEditable(editor);});

        label.remove();
    });
});

function DoMouseEnter(editor) {
    if (editor.attr("readonly") == true) {
        editor.animate({
            backgroundColor: '#F1FFB8'
            }, 200);
    }
}

function DoMouseLeave(editor) {
    if (editor.attr("readonly") == true) {
        editor.animate({
            backgroundColor: FindBackgroundColor(editor.parent())
            }, 700);
    }
}

function FindBackgroundColor(element) {
    var bg = element.css("background-color");
    
    if (bg == undefined || bg == "transparent") {
        var parent = element.parent();

        if (parent != undefined)
            return FindBackgroundColor(parent);
        else 
            return "#FFF";
    }
    else
        return bg;
}

function MakeEditable(editor) {
    editor.removeAttr("readonly");
    editor.css("cursor", "text");
    editor.attr("oldValue", trim(editor.val()));

    editor.animate({
        backgroundColor: '#FFF',
        borderBottomColor: '#000',
        borderTopColor: '#000',
        borderLeftColor: '#000',
        borderRightColor: '#000'
        }, 300);
}

function RemoveEditable(editor) {
    editor.attr("readonly", "true");
    editor.css("cursor", "pointer");

    var oldValue = editor.attr("oldValue");
    var newValue = trim(editor.val());

    if (newValue.length == 0 && editor.hasClass("required")) {
        alert("It's required");
        editor.val(oldValue);
        return;
    }

    if (editor.hasClass("number") && parseInt(newValue) != newValue) {
        alert("NOT A NUMBER");
        editor.val(oldValue);
        return;
    }

    if (oldValue != newValue) {
        ValueChanged(editor, oldValue, newValue);
    }

    var bg = FindBackgroundColor(editor.parent());

    editor.animate({
        backgroundColor: bg,
        borderBottomColor: bg,
        borderTopColor: bg,
        borderLeftColor: bg,
        borderRightColor: bg
        }, 300);
}

function SaveValue(field, oldValue, newValue) {
    alert("The function Save Value should be implemented on this page!");

    SaveComplete(field);
}

function ValueChanged(field, oldValue, newValue) {
    var fieldId = field.attr("id") + "_Saved";

    $("body").before("<div id='"+fieldId+"'></div>");

    var successDiv = $("#" + fieldId);
    successDiv.attr("title", "Saving...");
    successDiv.css("position", "absolute");
    successDiv.css("width", 16);
    successDiv.css("height", 16);
    successDiv.css("border", "1px #CCC solid");
    successDiv.css("padding", 1);
    successDiv.css("background", "white url(/Images/loader.gif) no-repeat center center");
    successDiv.css("display", "none");
    successDiv.css("top", field.offset().top + 2);
    successDiv.css("left", field.offset().left + field.width() + 10);

    successDiv.fadeIn("slow");

    SaveValue(field, oldValue, newValue);
}

function SaveComplete(field) {
    var fieldId = field.attr("id") + "_Saved";
    var successDiv = $("#" + fieldId);
    
    successDiv.attr("title", "Save Complete");
    successDiv.css("background", "white url(/Images/check.png) no-repeat center center");

    window.setTimeout(function() {
        successDiv.fadeOut("slow", function(){successDiv.remove();});
    }, 2000);
}

// this section is generic helper methods for dealing with forms
function trim(string) {
    if (string == undefined)
        return "";

    return string.replace(/^\s*/, "").replace(/\s*$/, "");
}

function validateRequired(parent, addMessage) {
    var result = true;

    $(parent + " .required").each(function () {

        var cleanedValue = trim($(this).val());

        if (cleanedValue == $(this).attr("default"))
            cleanedValue = "";

        if (cleanedValue.length == 0) {
            $(this).parent().addClass("input-error");

            if (addMessage)
                $(this).siblings("span:first").text("Required");

            result = false;
        }
        else {
            $(this).parent().removeClass("input-error");

            if (addMessage)
                $(this).siblings("span:first").text("");
        }
    });

    return result;
}

function validateEmail(parent, addMessage) {
    var result = true;

    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    $(parent + " .email").each(function () {
        var address = $(this).val();

        if (reg.test(address) == false) {
            $(this).parent().addClass("input-error");

            if (addMessage)
                $(this).siblings("span:first").text("Invalid email format");

            result = false;
        }
        else {
            $(this).parent().removeClass("input-error");

            if (addMessage)
                $(this).siblings("span:first").text("");
        }
    });

    return result;
}

function validateNumber(parent, addMessage) {
    var result = true;

    $(parent + " .number").each(function () {
        var number = $(this).val();

        if (number.length > 0 && parseInt(number) != number) {
            $(this).parent().addClass("input-error");

            if (addMessage)
                $(this).siblings("span:first").text("That's not a number");

            result = false;
        }
        else {
            $(this).parent().removeClass("input-error");

            if (addMessage)
                $(this).siblings("span:first").text("");
        }
    });

    return result;
}

function handleDefaults() {
    $(".default").each(function () {
        var defaultValue = trim($(this).attr("default"));
        $(this).addClass("input-default-text");
        $(this).val(defaultValue);

        $(this).focus(function () {
            $(this).removeClass("input-default-text");
            if (trim($(this).val()) == defaultValue) {
                $(this).val("");
            }
        });

        $(this).blur(function () {
            if ($(this).val().length == 0) {
                $(this).val(defaultValue);
                $(this).addClass("input-default-text");
            }
        });
    });
}

var leftToasts = new Array();
var rightToasts = new Array();
var topToasts = new Array();
var bottomToasts = new Array();

function MakeToast(title, content, location) {
    var toastId = "TOAST_" + new Date().getMilliseconds() + "-" + new Date().getSeconds();

    $("body").append("<div id='" + toastId + "' />");

    var toast = $("#" + toastId);
    toast.addClass("toast");
    toast.css("position", "absolute");

    toast.append("<div class='toast-header'>" + title + "</div>");
    toast.append("<div class='toast-body'>" + content + "</div>");
    
    if (location == "left") {
        toast.css("top", 40 + (leftToasts.length * (toast.height() + 15))); 
        toast.css("left", 0 - toast.width());
        toast.animate({left: 0}, {duration: 600, easing: "easeOutBack"});
        
        window.setTimeout(function() {
            toast.animate({left: 0 - toast.width()}, {duration: 600, easing: "easeOutCirc", complete: function() {toast.remove();}});
            
            leftToasts.shift();

            for (var i = 0; i < leftToasts.length; i++) {
                var otherToast = leftToasts[i];
                var currentTop = otherToast.css("top").replace("px" , "");

                otherToast.animate({top: currentTop - toast.height() - 15}, {duration: 400, easing: "easeOutCirc"});
            }
        }, 8000);
        
        leftToasts.push(toast);
    }
    else if (location == "right") {
        var oldWidth = toast.css("width").replace("px", "");

        toast.css("overflow", "hidden");
        toast.css("top", 40 + (rightToasts.length * (toast.height() + 15))); 
        toast.css("right", 0);// - toast.width());
        toast.css("width", 0);

        toast.animate({right: 0, width: oldWidth}, {duration: 600, easing: "easeOutBack"});
        
        window.setTimeout(function() {
            toast.animate({right: 0 - toast.width()}, {duration: 600, easing: "easeOutCirc", complete: function() {toast.remove();}});
            
            rightToasts.shift();

            for (var i = 0; i < rightToasts.length; i++) {
                var otherToast = rightToasts[i];
                var currentTop = otherToast.css("top").replace("px" , "");

                otherToast.animate({top: currentTop - toast.height() - 15}, {duration: 400, easing: "easeOutCirc"});
            }
        }, 8000);

        rightToasts.push(toast);
    }
    else if (location == "top") {
        toast.css("top", 0 - toast.height()); 
        toast.css("right", 40 + (topToasts.length * (toast.width() + 15)));
        toast.animate({top: 0}, {duration: 600, easing: "easeOutBack"});
        
        window.setTimeout(function() {
            toast.animate({top: 0 - toast.height()}, {duration: 600, easing: "easeOutCirc", complete: function() {toast.remove();}});
            
            topToasts.shift();

            for (var i = 0; i < topToasts.length; i++) {
                var otherToast = topToasts[i];
                var currentRight = otherToast.css("right").replace("px" , "");

                otherToast.animate({right: currentRight - toast.width() - 15}, {duration: 400, easing: "easeOutCirc"});
            }
        }, 8000);

        topToasts.push(toast);
    }
    else {
        var oldHeight = parseInt((toast.css("height").replace("px", "")), 10);
        var newTop = $(window).height() + $(window).scrollTop() - 7;
        toast.css("top", newTop);

        //toast.css("top", $("body").height() + $(window).scrollTop() - 8); 
        toast.css("right", 40 + (bottomToasts.length * (toast.width() + 15)));
        toast.css("height", 0);
        toast.animate({top: newTop - oldHeight - 1, height: oldHeight}, {duration: 600, easing: "easeOutBack"});
        
        window.setTimeout(function() {
            toast.animate({top: newTop - 1, height: 0}, {duration: 600, easing: "easeOutCirc", complete: function() {toast.remove();}});
            
            bottomToasts.shift();

            for (var i = 0; i < bottomToasts.length; i++) {
                var otherToast = bottomToasts[i];
                var currentRight = otherToast.css("right").replace("px" , "");

                otherToast.animate({right: currentRight - toast.width() - 15}, {duration: 400, easing: "easeOutCirc"});
            }
        }, 8000);

        bottomToasts.push(toast);
    }
}
