﻿$.fn.centerInClient = function (options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
        container: window,    // selector of element to center in
        completeHandler: null
    };
    $.extend(opt, options);

    return this.each(function (i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;
        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

function defaultAjaxPostError(res) {
    var obj;
    try {
        obj = JSON.parse(res.responseText);
    } catch (e) {
        //alert(res);
        return false;
    }
    errorText = obj.ExceptionType + ': ' + obj.Message + obj.StackTrace;
    if (typeof showNotificationMessages == 'function') {
        showNotificationMessages(errorText, true);
    } else {
        alert(errorText);
    }
}

function ajaxPost(url, data, success, error) {
    if (error === undefined) error = defaultAjaxPostError;
    $.ajax({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: success,
        error: error
    });
}

jQuery.fn.disable = function () {
    this.find('input, select, submit, a').addClass('controlDisabled disabled')
        .attr('disabled', true)
        .bind('click.disable', function (e) {
            e.preventDefault;
            return false;
        });
    this.animate({ 'opacity': '0.5' });
    this.addClass('controlDisabled');
};


jQuery.fn.enable = function () {
    this.find('input, select, submit, a').removeClass('controlDisabled disabled')
        .removeAttr('disabled')
        .unbind('click.disable');
    this.animate({ 'opacity': '1' });
    this.removeClass('controlDisabled');
};


function disableControls() {
    $('.controlDisabled').disable();
}

function disableAutoCompletes() {
    $('input[type=text], textarea').attr('autocomplete', 'off');
}

function MakeSeoFriendly(str) {
    if (typeof (str) === 'undefined') return null;
    if (str.length == 0) return "";
    str = str.replace("'", "").replace("`", "").toLowerCase();
    //'TODO: insert diametrics code here
    str = str.replace(/[^a-zA-Z\-0-9]/g, "-");
    str = str.replace(/[\-]{2,}/g, "-");
    if (str.substring(0, 1) == '-') str = str.substring(1);
    len = str.length;
    last_char = str.charAt(len - 1);
    if (last_char == '-') str = str.substring(0, len - 1);
    return (str);
}

function RemoveDefaultValues() {
    $('.RemoveDefaultValue').each(
		function () {
			if (this.value == $(this).attr('defaultvalue')) {
			    this.value = '';
			}
		}
	);
}

function RestoreDefaultValues() {
    $('.RemoveDefaultValue').each(
		function () {
		    if (this.value == '') {
		        this.value = $(this).attr('defaultvalue');
		    }
		}
	);
}

function UpdateSessionScreenResolution() {
    ajaxPost('/system/services/Session.asmx/UpdateScreenResolution',
    { Width: $(window).width(), Height: $(window).height() },
    function (res) {
        //
    });
}

function ValidateEmail(value) {
    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

var validator;
function SetupJQueryValidation() {
    validator = $("#aspnetForm").validate({ onsubmit: false });
    $('.validationGroup .causesValidation').click(ValidateAndSubmit);
    $('.validationGroup.interceptEnter :input:text').keydown(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).blur();
            e.preventDefault();
            $(this).focus();
        }
    });
}

function InterceptEnter(id, fn) {
    $(id + ' :input:text').keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            fn();
            e.preventDefault();
            return false;
        }
    });   
}

function ValidateGroup(g) {
    allValid = true;
    $(g).find(':input').each(function (i, item) {
        if ($(item).val() == '' && !$(item).hasClass('required')) {
            // bug in jQuery / validator... force respecting 'required'
            return;
        }
        isValid = $(item).valid();
        if (isValid == false) {
            if (window.console) {
                console.log('Error validating ' + $(item).attr('id'));
            }
            allValid = false;
        }
    });
    return allValid;
}

function ValidateAndSubmit(evt) {
    group = $(evt.currentTarget).closest('.validationGroup'); //.closest('.validationGroup'); //parents('.validationGroup');
    if (!ValidateGroup(group)) {
        evt.preventDefault();
    }
}
