﻿function ShowBalloonTips() {
    $("[balloontip]").each(function () {
        var jElement = $(this);
        jElement.balloonTip(jElement.attr("balloontip"), { relativePosition: 'bottom-left', insertAt: 'body' });
    });
}

function ShowBalloonTip(element) {
    var jElement = $(element);
    jElement.balloonTip(jElement.attr("balloontip"), { relativePosition: 'bottom-left', insertAt: 'body' });
}

function ToggleImageSize(smallWidth, largeWidth) {
    var jElement = $(window.event.srcElement)

    var parentTop = jElement.parent().position().top;
    var parentLeft = jElement.parent().position().left;

    if (jElement.width() === smallWidth) {
        jElement
            .css("position", "absolute")
            .animate({ top: parentTop, left: parentLeft }, 0)
            .css("border", "4px solid #000000")
            .animate({ top: 20, left: 20, width: largeWidth }, "slow")
            ;
    } else {
        jElement.animate({ top: parentTop, left: parentLeft, width: smallWidth }, "slow", function () {
            $(this)
                .css("position", "relative")
                .animate({ top: 0, left: 0 }, 0)
                .css("border", "none")
                ;
        });
    }
}

function RequiredFieldsPopulated() {
    var isOkay = true;

    // remove any old and stale "input required" fields
    $(".InputValidationFailed").remove();

    // go looking within any DEtailsView controls for inputs. This is a special case because we
    // have to put the CSS marker class onto the container as we don't get access to the individual
    // controls from the server side.
    $(".DetailsView .Required").each(function () {

        if ($("input", $(this).parent()).val() == "") {
            isOkay = false;
        }

        if ($("select", $(this).parent()).val() == "") {
            isOkay = false;
        }

        if ($("textarea", $(this).parent()).val() == "") {
            isOkay = false;
        }

    });

    // now just go and look for any individual controls that have validation regexes on them.
    $("[ValidationRegex]:visible").each(function () {
        var jElement = $(this);
        var content = jElement.val();
        var expr = jElement.attr("ValidationRegex");
        var regex = new RegExp(expr, "i");
        if (!regex.test(content)) {
            var message = jElement.attr("ValidationMessage");
            jElement.after('<span class="InputValidationFailed">' + message + '</span>');
            isOkay = false;
        }
    });

    return isOkay;
}

function OnFormSubmit(event) {
    if (!RequiredFieldsPopulated()) {
        // don't use alert(...) or similar - there should already be validators visible on the
        // page, and personally I want to hit people with a stick when they steal focus from me.  -andrewh 6/7/10
        return false;
    }

    return true;
}

function OnWizardStepSubmit(event) {
    return ValidateFormAndClickButton(event, "StepNextButton");
}

function ValidateFormAndClickButton(event, buttonId) {
    // FIXME: This is unpleasant code but there is currently no other way of achieving what we need to do. (Andy Jackson 14/7/10)
    // We need to disable the default form submit that occurs on this page when the user hits the return/enter key
    // this is because we don't want to submit this form, rather we want to move to the next step (i.e. hit the "next >>" button).
    // So we return false from here, and instead hit the StepNextButton. However the event we create here is not complete, so the global.js
    // can not prevent the event bubbling up and causing the next button to be pressed even when the form has validation errors. So we have to 
    // do the check ourselves and then only trigger the step button if the form passes validation.
    if (event.keyCode == 13) {
        var ret = OnFormSubmit();
        if (ret == true) {
            var e = jQuery.Event("click");
            $("[id$=" + buttonId + "]").trigger(e);
        }
        return false;
    }
}

function OnLinkClicked(event) {
    var jElement = $(event.target);

    if (jElement.text() === "Delete") {
        return confirm("This will delete the currently record. Are you sure?");
    }

    // detail views
    if (jElement.is("a:contains(Update),a:contains(Insert),a:contains(Save),a:contains(Create)")) {
        return OnFormSubmit(event);
    }

    // wizard buttons
    if (jElement.is("input[type=submit][id$=StartNextButton],input[type=submit][id$=StepNextButton],input[type=submit][id$=FinishButton]")) {   
        return OnFormSubmit(event);
    }
}

$("a").live("click", function (event) { return OnLinkClicked(event); });
$("input[type=submit]").live("click", function (event) { return OnLinkClicked(event); });

window.RequiredFieldsToAnnotate = [];

function AnnotateRequiredFields() {
    var element = Array.dequeue(window.RequiredFieldsToAnnotate);
    if (element) {
        var jElement = $(element);
        var needsAnnotation = true;

        var jSpan = jElement.children("span:last-child");
        if (jSpan.length > 0) {
            if (jSpan.text() == "*") {
                needsAnnotation = false;
            }
        }

        if (needsAnnotation) {
            jElement.append("<span style='color: #ff0000;' title='Required field.'>*</span>");
        }

        window.setTimeout(AnnotateRequiredFields, 0);
    }
}

function EnqueueRequiredFields() {
    $(".DetailsView .Required").each(function () {
        Array.enqueue(window.RequiredFieldsToAnnotate, this);
    });

    window.setTimeout(AnnotateRequiredFields, 0);
}

function UpdateLinkButtonText() {

    // change all "Insert" and "Update" buttons to "Save"
    $("a[href]:contains(Insert),a[href]:contains(Update)").each(function () {
        var jLink = $(this);
        if (jLink.text() === "Insert") jLink.text("Save");   // check for *exactly* "Insert"
        if (jLink.text() === "Update") jLink.text("Save");   // check for *exactly* "Update"
    });
}

function OnPageLoad() {
    window.setTimeout(EnqueueRequiredFields, 0);
    window.setTimeout(UpdateLinkButtonText, 0);
}

Sys.Application.add_load(OnPageLoad);

    
