﻿$(function() {

    $.nm = function(s) {
        $.nyroModalManual($.extend({
            endShowContent: function() {
                $(window).trigger('resize.nyroModal');
            }
        }, s));
    }
    
    $.nmRemove = function() {
        $.nyroModalRemove();
    }    

    $.softAjax = function(s) {
        //s = {url: '', type: 'POST', data: {}, success: {}, showErrorPopUp: true, error: {}};
        s = $.extend({ url: '/', suppressErrors: false, type: 'POST', complete: function() { }, data: {}, success: function() { }, showErrorPopUp: true, error: null, recovery: null, disableRecovery: false }, s);  //Setup defaults
        if (!s.disableRecovery) {
            _LastExecuted = function() { $.softAjax(s) };
        }
        return $.ajax({
            type: s.type,
            url: s.url,
            data: s.data,
            complete: s.complete,
            success: function(results, x, y) {
                if ((results + '').indexOf('<!DOCTYPE html') >= 0) {
                    _Recovery = _LastExecuted //function() { lastExecuted };
                    loginPrompt();
                    return;
                }
                if (!results.Success && $.isFunction(s.error)) {
                    s.error(results)
                }
                else {
                    if (!results.Success && !s.suppressErrors) {
                        $.prettyPrompt({
                            title: 'Error',
                            message: 'Sorry there was an error processing your request.<br /> ' + results.ErrorMessage,
                            returnCallback: s.recovery
                        });
                    }
                    else {
                        /*
                        if ($.isFunction(lastExecuted)) {
                        lastExecuted();
                        lastExecuted = null;
                        }
                        else {
                        s.success(results);
                        }*/
                        s.success(results);
                    }

                }
            },
            error: function(request, status, errorThrown) {
                if (parseInt(request.status, 10) == 403 || parseInt(request.status, 10) == 302) {
                    _Recovery = _LastExecuted;
                    //$.prettyPrompt({ title: 'Authorization Required', message: 'That action is not authorized. You must first login.', callback: function(data){alert('aaa');} });
                    loginPrompt();
                }
                else {
                    if (s.error != null && $.isFunction(s.error)) {
                        s.error(request, status, errorThrown);
                    }
                    else if (!s.suppressErrors) {
                        //Before prompting we need to make sure there ins't an error already on screen.
                        if ($('.jqimessage h1:contains("Error")').length == 0) {
                            $.prettyPrompt({ title: 'Error', message: 'Sorry there was an error processing your request.<br /> ' });
                        }

                    }
                }
            }
        });
    }

    $.aj = function(s) {
        return $.softAjax(s);
    }

    $.prettyPrompt = function(s) {
        s = $.extend({ title: '', message: '', callback: null }, s);  //Setup defaults

        s.callback = (function(clicked, msg, formvals) {
            if (s.returnCallback) {
                s.returnCallback(clicked, msg, formvals);
            }
        });
        $.prompt(((s.title + '') == '' ? '' : '<h1>' + s.title + '</h1>') + '<p>' + s.message + '</p>', s);
    }

    $.pPrompt = function(s) {
        $.prettyPrompt(s);
    }

    $.fn.dValidate = function(s) {
        return $(this).validate($.extend(s, {
            errorPlacement: function(errorElement, inputElement) {
                inputElement.parent().children('label').addClass('formError');
            },
            highlight: function(inputElement, errorClass) {
                $(inputElement).parent().children('label').addClass('formError');
            },
            unhighlight: function(inputElement, errorClass) {
                $(inputElement).parent().children('label').removeClass('formError');
            }
        })
        );
    }

    jQuery.fn.dataScrapeFields = function(s) {
        s = $.extend({ customParsers: {}, attribute: 'data' }, s);

        var container = $(this);

        var resObj = {};
        $('[' + s.attribute + ']', container).each(function() {
            var element = $(this);
            var value = null;
            var dataField = element.attr(s.attribute);

            if ($.isFunction(s.customParsers[dataField])) {
                value = s.customParsers[dataField]({ sender: element });
            }
            else {
                value = element.val();
                if (element.is(':checked') == true) {
                    value = true;
                }
                else {
                    if (value == '' && element.attr('isNull') == 'true')
                        value = null;
                    if (element.attr('type') == 'checkbox') {
                        value = false;
                    }
                }
            }
            resObj[dataField] = value;
        })

        return resObj;

    }

    jQuery.fn.databindFields = function(s) {
        s = $.extend({ data: {}, attribute: 'data', customParse: {} }, s);
        s.data = s.data || {};
        var container = $(this);

        if (container == null)
            return;

        $('[' + s.attribute + ']', container).each(function() {
            var item = $(this);
            var value = null;
            var dataField = item.attr(s.attribute);
            if ($.isFunction(s.customParse[dataField])) {
                value = s.customParse[dataField]({ sender: item });
            }
            else {
                if (item.attr('type') == 'checkbox') {
                    if ((s.data[item.attr(s.attribute)] + '') == 'true') {
                        item.attr('checked', 'checked');
                    }
                    else {
                        item.removeAttr('checked');
                    }
                }
                else {
                    value = s.data[item.attr(s.attribute)];
                    if (value == null)
                        item.attr('isNull', 'true');
                    item.val(value);
                }

            }
        });
    }

    String.prototype.toDateFromMsSql = function() {
        //var dte = eval("new " + this.replace(/\//g, '') + ";");
	var dte = eval("new " + this.replace(/\//g, '').replace(/-\d+/g, '') + ";");
        dte.setMinutes(dte.getMinutes());
        return dte;
    }


});
