﻿$(function () {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(NiceConfirmInit);
    NiceConfirmInit();
});

var NICE_CONFIRM_TARGET_ON_SUCCESS = null;

function NiceConfirmInit() {
    /* HIGH LEVEL CONCEPT:
    *
    * Stop the original button from CONFIRMING anything. I.e. make it do what it's supposed to do.
    * Now hide it to stop the user clicking it.
    * Make a replica of the original minus the 'name','id' and 'onclick' attributes.
    * Add an attribute to this clone that stores the name of the element that it was cloned from.
    * Modify this clone so that clicking it opens a nice dialog.
    * If the users clicks 'confirm' click the original button.
    * The original button will "just do what it's supposed to" as we removed the confirm related script.
    *
    */

    //return false;
    if ($('#nice-confirm').length == 0) {
        throw "a div with id #nice-confirm must exist!";
    }

    $('#nice-confirm').dialog("destroy");
    $('#nice-confirm').dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        open: function (event, ui) {
            var el = $('.ui-widget-overlay');

            $($(el)[$(el).length - 1]).css('z-index', 10999);

            $('div[aria-labelledby="ui-dialog-title-nice-confirm"]').css('z-index', 11000);
        }
    });

    $('input[onclick]').each(function () {
        if ($(this)[0].getAttributeNode('onclick').value.toString().indexOf("return confirm") > -1) {
            //copy the element
            var el = $(this).clone(false);

            // Get the original confirmation content
            var originalOnClickAttr = $(this)[0].getAttributeNode('onclick').value.toString();
            var originalOnClickAttrSplit = originalOnClickAttr.split(";");
            var originalConfirmationScript = originalOnClickAttrSplit[0];
            originalOnClickAttrSplit.splice(0, 1, "return true");
            originalOnClickAttr = '';
            for (var i in originalOnClickAttrSplit) {
                if (i != "indexOf" && originalOnClickAttrSplit[i].length > 0) {
                    originalOnClickAttr += originalOnClickAttrSplit[i] + ';';
                }
            }
            //originalOnClickAttr = originalOnClickAttr.replace("}", "");

            var confirmMessage = originalConfirmationScript.split("'")[1];

            // Stop the original button from CONFIRMING anything so that when we click it, it just does what it is supposed to 
            //var ModifiedClickFunction = new Function(originalOnClickAttr);
            //$(this).attr('onclick', '').click(ModifiedClickFunction);

            if (originalOnClickAttr == "") {
                $(this).attr('onclick', '').unbind('click');
                $(this)[0].removeAttribute('onclick');
            } else {
                $(this).attr('onclick', '').unbind('click');
                $(this)[0].removeAttribute('onclick');
                $(this)[0].setAttribute('onclick', originalOnClickAttr);
            }

            $(this).attr('title', $(this)[0].getAttributeNode('onclick').value);


            // Remove unwanted parts from the clone
            //el = RemoveAttributeProperly($(el).outerHTML(), "onclick");
            //el = RemoveAttributeProperly($(el).outerHTML(), "id");
            //el = RemoveAttributeProperly($(el).outerHTML(), "name");

            el = purgeAttributes(el[0]);

            $(el)[0].removeAttribute('onclick');
            $(el)[0].removeAttribute('id');
            $(el)[0].removeAttribute('name');

            $(el).removeAttr('onclick');
            $(el).unbind('click');
            $(el).removeAttr('id');
            $(el).removeAttr('name');

            $(el)[0].onclick = null;

            // paste the modified clone next to the original with our on click methods attached
            $(el)
            .attr('data-elementNameToClickOnSuccess', $(this).attr('name'))
            .attr('data-message', confirmMessage)
            .insertAfter($(this))
            .unbind('click')
            .click(function () {
                NiceConfirm($(this).attr('data-message'), $(this).attr('data-elementNameToClickOnSuccess'), false, null);
                return false;
            });

            //Hide the original
            $(this).hide();
        }
    });
}

function NiceAlert(msg) {
    NiceConfirm(msg, "#xxxxxxxxxxxxxxxxxxxxxxxxxx", true, function () { });
    $('#nice-confirm-btnCancel').hide();
}

function NiceConfirm(msg,elementIdToClickOnSuccess,clickElementDirectly,cancelFunctionOrNull) {
    //$(this).click();
    $('#nice-confirm-content-surrogate').html(msg);

    NICE_CONFIRM_TARGET_ON_SUCCESS = elementIdToClickOnSuccess;

    $('#nice-confirm-btnConfirm')
        .unbind('click')
        .css('cursor', 'pointer')
        .click(function () {
            $('#nice-confirm').dialog('close');
            if (clickElementDirectly) {
                $(NICE_CONFIRM_TARGET_ON_SUCCESS).click();
            } else {
                $('input[name*="' + NICE_CONFIRM_TARGET_ON_SUCCESS + '"]').click();
            }
        })
        $('#nice-confirm-btnCancel').show().css('cursor', 'pointer').unbind('click').click(function () {
            $('#nice-confirm').dialog('close');
            if (cancelFunctionOrNull !== null) { cancelFunctionOrNull(); }
        });
    $('#nice-confirm').dialog('open');
    return false;
}

function RemoveAttributeProperly(el, attr) {
    //Remove onclick event
    //  this is a lot harder than it seems! as jquery doesn't remove inline onclick attributes!! :(
    //  This implementation:
    //      * finds the part left of the onclick attribute
    //      * finds the second double quote after the onclick attribute
    //      * concatenates these two parts back together again.

    attributes = el.split('=');

    attr = attr + "=";
    var tempStr = el;
    var indexOfOnclick = tempStr.indexOf(attr);
    var leftPart = tempStr.substr(0, tempStr.indexOf(attr));
    var firstRelevantDblQuote = indexOfOnclick + attr.length;
    var rightPart = tempStr.substr(firstRelevantDblQuote, tempStr.length - firstRelevantDblQuote);
    var splitRightPart = rightPart.split('"');
    splitRightPart.splice(0, 2);
    el = leftPart;
    for (var i in splitRightPart) {
        el += splitRightPart[i] + '"';
    }
    return purgeAttributes(el);
}

function purgeAttributes(el) {
    //keep these attributes
    var whitelist = ["colspan", "color", "align", "onmouseover", "type", "src"];
    for (var i = 0; i < el.attributes.length; i++) {
        var attr = el.attributes.item(i);
        var whiteListCheck = false;
        //loop through whitelist
        for (var j = 0; j < whitelist.length; j++) {
            if (attr.nodeName === whitelist[j]) {
                whiteListCheck = true;
                break;
            }
        }
        if (!whiteListCheck) {
            //second parameter means a case-sensitive search
            el.removeAttribute(attr.nodeName, 1);
        }
    }
    return el;
}

function test() {
    alert('test');
}
