﻿function numericKeyUpHandler(event) {
    var val = removeCommas($(this).val());
    var maxLength = $(this).attr('maxlength');
    while (val.indexOf(",") != -1) {
        val = removeCommas(val);
    }
    //console.log(val);
    //console.log(maxLength);
    $(this).val(thousandSeparator(val));
    if (maxLength > 0 && maxLength != undefined && $(this).val().length > maxLength) {
        $(this).val($(this).val().substring(0, maxLength));
        var val = removeCommas($(this).val());
        while (val.indexOf(",") != -1) {
            val = removeCommas(val);
        }
        //console.log(val);
        $(this).val(thousandSeparator(val));
    }
}

var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67;

$(document).ready(function () {
    $(document).keydown(function (e) {
        if (e.keyCode == ctrlKey) {
            window.ctrlDown = true;
            //console.log('control down');
        }

    }).keyup(function (e) {
        if (e.keyCode == ctrlKey) {
            window.ctrlDown = false;
            //console.log('control up');
        }
    });

    $(".sglist tr").live("click", function () {
        $(this).parent().children("tr").each(function () {
            $(this).css("background-color", "");
        });

        $(this).css("background-color", "#FFD1D1");
    });

    var timeOut = null;
    $(".userIncrementalFilter").live("keyup", function () {
        if (timeOut != null) {
            clearTimeout(timeOut);
            timeOut = null;
        }

        var targetDropdownID = $(this).attr("targetDropDownID");
        var targetUrl = $(this).attr("targetUrl");
        var filterValue = $(this).val();

        timeOut = setTimeout(function () {
            $.getJSON(targetUrl,
                        { filter: filterValue },
                        function (data) {
                            $("#" + targetDropdownID).empty()
                                .append($("<option>").val("0").text(""));

                            $.each(data, function (index, value) {
                                var option = $("<option>")
                                    .val(value.id)
                                    .text(value.text)
                                    .appendTo("#" + targetDropdownID);
                            });
                        });
        }, 500);
    });

    $(".jumptoPage").live("click", function (e) {

        var pageNumber = $(this).parent().children(":text").val();
        var hiddenAnchor = $(this).parent().children(".hiddenAnchor");
        var url = $(hiddenAnchor).attr("href");

        url = url.replace("pagenumber", pageNumber);

        $(hiddenAnchor).attr("href", url);
        $(hiddenAnchor).click();
    });

    $(".pagenavigator :text").live("keypress", function (e) {
        if (e.which == 13) {
            $(".jumptoPage", $(this).parent()).click();
        }

    });
});


function numericKeyDownHandler(event) {

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) // 0-9 or numpad 0-9
    {
        // check textbox value now and tab over if necessary
    }
    else if (!(window.ctrlDown && (event.keyCode == vKey || event.keyCode == cKey)) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39 && event.keyCode != 9 && !(event.keyCode >= 112 && event.keyCode <= 123)) // not esc, del, left or right
    {
        event.preventDefault();
    }
    // else the key should be handled normally
}

function decimalKeyDownHandler(event) {
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) // 0-9 or numpad 0-9
    {
        // check textbox value now and tab over if necessary
    }
    else if (!(window.ctrlDown && (event.keyCode == vKey || event.keyCode == cKey)) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39 && event.keyCode != 9 && !(event.keyCode >= 112 && event.keyCode <= 123) && event.keyCode != 110 && event.keyCode != 190) // not esc, del, left or right
    {
        event.preventDefault();
    }
    // else the key should be handled normally
}

function removeCommas(nStr) {
    val = nStr;
    while (val.indexOf(",") != -1) {
        val = val.replace(',', '');
    }
    return val;
}


function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function thousandSeparator(n, sep) {
    var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
            sValue = n + '';

    if (sep === undefined) { sep = ','; }
    while (sRegExp.test(sValue)) {
        sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
    }
    return sValue;
}


function loadSimpleDialog(tag, event, target, updateList, minWidth, minHeight, formName, modal, dialog) {
    event.preventDefault();
    var $loading = $('<img src="@Url.Content("~/Content/images/ajaxLoading.gif")" alt="loading" class="ui-loading-icon">');
    var $url = $(tag).attr('href');
    var $title = $(tag).attr('title');
    var sgTitle = $(tag).attr('sgtitle');
    if (sgTitle == undefined || sgTitle == '')
        sgTitle = $title;

    var position = GetSelectorLocation(tag);
    var $dialog = $('<div></div>');

    var aftercompleteUrl = '';
    if ($(tag).attr('sgaftercompleteUrl') != undefined)
        aftercompleteUrl = $(tag).attr('sgaftercompleteUrl');

    var aftercompleteTargetID = '';
    if ($(tag).attr('sgaftercompleteTargetID') != undefined)
        aftercompleteTargetID = '#' + $(tag).attr('sgaftercompleteTargetID');

    if ($(tag).attr('sgtarget') != undefined)
        target = '#' + $(tag).attr('sgtarget');

    if ($(tag).attr('sgdialog') != undefined) {
        dialog = '#' + $(tag).attr('sgdialog');
        $dialog = $(dialog);
    }

    var maxHeight = "0px";
    if ($(tag).attr('sgmaxheight') != undefined)
        maxHeight = $(tag).attr('sgmaxheight');

    if (formName == undefined)
        formName = "form";

    if ($(tag).attr('sgform') != undefined)
        formName = $(tag).attr('sgform');

    if (modal == undefined)
        modal = false;
    $dialog.empty();
    $dialog
			.append($loading)
			.load($url, function (response, status, xhr) {
			    if (minWidth == undefined)
			        minWidth = '500px';
			    if (minHeight == undefined)
			        minHeight = '200px';
			    $dialog.css('min-width', minWidth);
			    $dialog.css('max-width', '850px');
			    $dialog.css('min-height', minHeight);
			    $dialog.css('padding', "0");
			    if (maxHeight != undefined && maxHeight != "0px") {
			        $dialog.css({ 'max-height': maxHeight, 'overflow-y': 'auto' })
			    }

			    $dialog.dialog('option', 'position', position);
			    if (xhr.status == 401) {
			        // perform a redirect to the login page since we're no longer authorized
			        RedirectToLoginPage();
			    }
			    else if (xhr.status == 502 || xhr.status == 504) {
			        ShowProxyError(xhr.status);
			    }
			    else if (xhr.status == 200) {
			        $dialog.dialog('open');
			    }
			    else {
			        var o = extraxtError(xhr.responseText);
			        displayError(o, status);
			    }
			})
			.dialog({
			    autoOpen: false
				, title: sgTitle
				, minHeight: 200
				, minWidth: 500
				, width: 'auto'
                , height: 'auto'
				, show: 'fade'
				, hide: 'fade'
                , position: 'center'
                , modal: modal
                , stack: true
                , resize: function (e, ui) {
                    if ($dialog.parent().width() >= parseInt($dialog.css('max-width'), 10)) {
                        $dialog.parent().width($dialog.css('max-width'));
                        $(this).width($dialog.css('max-width'));
                    }
                },
                close: function (e, ui) {
                    $dialog.empty();
			    }
			});
    if ($.browser.msie) {
        $dialog.bind("dialogopen", function (event, ui) {
            // fix for width:auto in IE
            var jqDialog = jQuery(this);
            var parent = jqDialog.parent();
            var contentWidth = jqDialog.width();
            parent.find('.ui-dialog-titlebar').each(function () {
                jQuery(this).width(contentWidth);
            });
            parent.width(contentWidth + 26);
            jqDialog.dialog('option', 'position', 'center');

            // fix for scrollbars in IE
            //jQuery('body').css('overflow', 'hidden');
            jQuery('.ui-widget-overlay').css('width', '100%');
        }).bind("dialogclose", function (event, ui) {
            // fix for width:auto in IE
            jQuery(this).parent().css("width", "auto");

            // fix for scrollbars in IE
            jQuery('body').css('overflow', 'auto');
        });
    }
    $dialog.dialog("option", "buttons", {
        "تایید": function () {
            var dlg = $(this);
            $.ajax({
                url: $url,
                type: 'POST',
                data: $("#" + formName).serialize(),
                success: function (response) {
                    var isValidVal = $('#IsEntityValid', response).val();
                    var isValid = isValidVal == undefined || isValidVal == "True";

                    if (!isValid) {
                        $dialog.html(response);
                    }
                    else {
                        if (updateList) {
                            $(target).html(response);
                            $("#ajaxResult").hide().html('اطلاعات ذخیره شد').fadeIn(300, function () {
                                var e = this;
                                setTimeout(function () { $(e).fadeOut(400); }, 2500);
                            });
                        }
                        else {
                            dlg.dialog('close');
                            dlg.empty();
                            alert('اطلاعات ذخیره شد');
                        }
                        if (aftercompleteUrl != '') {
                            $.ajax({
                                url: aftercompleteUrl,
                                type: 'GET',
                                success: function (response) {
                                    if ($.browser.msie) {
                                        //there is a bug in jquery replacewith not working properly
                                        $(aftercompleteTargetID).replaceWith(response);
                                    } else {
                                        $(aftercompleteTargetID).replaceWith(response);
                                    }
                                },
                                error: function (xhr) {
                                    if (xhr.status == 401) {
                                        // perform a redirect to the login page since we're no longer authorized
                                        RedirectToLoginPage();
                                    }
                                    else if (xhr.status == 502 || xhr.status == 504) {
                                        ShowProxyError(xhr.status);
                                    }
                                    else if (xhr.status == 400) {
                                        /* display validation errors in edit dialog */
                                        var o1 = extraxtError(xhr.responseText);
                                        dlg.html(o1, xhr.status);
                                    }
                                    else {
                                        /* display other errors in separate dialog */
                                        var o = extraxtError(xhr.responseText);
                                        displayError(o, status);
                                    }

                                }
                            });
                        }
                        dlg.dialog('close');
                        dlg.empty();
                    }

                },
                error: function (xhr) {
                    if (xhr.status == 401) {
                        // perform a redirect to the login page since we're no longer authorized
                        RedirectToLoginPage();
                    }
                    else if (xhr.status == 502 || xhr.status == 504) {
                        ShowProxyError(xhr.status);
                    }
                    else if (xhr.status == 400) {
                        /* display validation errors in edit dialog */
                        var o1 = extraxtError(xhr.responseText);
                        dlg.html(o1, xhr.status);
                    }
                    else {
                        /* display other errors in separate dialog */
                        var o = extraxtError(xhr.responseText);
                        displayError(o, status);
                    }

                }
            });
        },
        "انصراف": function () {
            $(this).dialog("close");
            $(this).empty();
        }

    });
};

function RedirectToLoginPage() {
    //var host = window.location.host;
    //window.location.assign(window.location.protocol+"//"+ host + "/Account/LogOn?ReturnUrl=" + window.location.pathname) 
    window.location.replace("/Account/LogOn?ReturnUrl=" + window.location.pathname);
}


function GetSelectorLocation(selector) {
    var myDialogX = $(selector).offset().left;
    var myDialogY = $(selector).offset().top + $(selector).outerHeight() - $(document).scrollTop();

    if ((myDialogX + 250) > $(window).width())
        myDialogX = $(window).width() - 270;

    return [myDialogX, myDialogY];
}

function simpleDialog(tag, event, target, modal) {
    event.preventDefault();
    var $loading = $('<img src="@Url.Content("~/Content/images/ajaxLoading.gif")" alt="loading" class="ui-loading-icon">');
    var $url = $(tag).attr('href');
    var $title = $(tag).attr('title');
    var sgTitle = $(tag).attr('sgtitle');
    if (sgTitle == undefined || sgTitle == '')
        sgTitle = $title;
    if ($(tag).attr('sgtarget') != undefined)
        target = '#' + $(tag).attr('sgtarget');
    var dialog = '';
    if ($(tag).attr('sgdialog') != undefined)
        dialog = '#' + $(tag).attr('sgdialog');
    else
        dialog = '#dialog';

    var maxHeight = "0px";
    if ($(tag).attr('sgmaxheight') != undefined)
        maxHeight = $(tag).attr('sgmaxheight');

    var formName = "form";
    if ($(tag).attr('sgform') != undefined)
        formName = $(tag).attr('sgform');
    
    var aftercompleteUrl = '';
    if ($(tag).attr('sgaftercompleteUrl') != undefined)
        aftercompleteUrl = $(tag).attr('sgaftercompleteUrl');

    var aftercompleteTargetID = '';
    if ($(tag).attr('sgaftercompleteTargetID') != undefined)
        aftercompleteTargetID = '#' + $(tag).attr('sgaftercompleteTargetID');

    //var $dialog = $('<div></div>');
    var $dialog = $(dialog);
    if (modal == undefined)
        modal = true;
    $dialog.empty();
    $dialog
            .append($loading)
			.load($url, function (response, status, xhr) {
			    minWidth = '500px';
			    $dialog.css('min-width', minWidth);
			    $dialog.css('max-width', '850px');
			    $dialog.css('padding', "0");
			    if (maxHeight != undefined && maxHeight != "0px") {
			        $dialog.css({ 'max-height': maxHeight, 'overflow-y': 'auto' })
			    }

			    if (xhr.status == 401) {
			        // perform a redirect to the login page since we're no longer authorized
			        RedirectToLoginPage();
			    }
			    else if (xhr.status == 502 || xhr.status == 504) {
			        ShowProxyError(xhr.status);
			    }
			    else if (xhr.status == 200) {
			        $dialog.dialog('open');
			    }
			    else {
			        var o = extraxtError(xhr.responseText);
			        displayError(o, status);
			    }

			})
			.dialog({
			    autoOpen: false
				, title: sgTitle
				, minHeight: 200
				, minWidth: 500
				, width: 'auto'
                , height: 'auto'
				, show: 'fade'
				, hide: 'fade'
                , position: 'center'
                , modal: modal
                , stack: false
                , resize: function (e, ui) {
                    if ($dialog.parent().width() >= parseInt($dialog.css('max-width'), 10)) {
                        $dialog.parent().width($dialog.css('max-width'));
                        $(this).width($dialog.css('max-width'));
                    }
                },
			    close: function (e, ui) {
			        afterDialogClose(aftercompleteUrl, aftercompleteTargetID);
			        $dialog.css('max-height', '');
			        $dialog.empty();
			    }
			});
    if ($.browser.msie) {
        $dialog.bind("dialogopen", function (event, ui) {
            // fix for width:auto in IE
            var jqDialog = jQuery(this);
            var parent = jqDialog.parent();
            var contentWidth = jqDialog.width();
            parent.find('.ui-dialog-titlebar').each(function () {
                jQuery(this).width(contentWidth);
            });
            parent.width(contentWidth + 26);
            jqDialog.dialog('option', 'position', 'center');

            // fix for scrollbars in IE
            //jQuery('body').css('overflow', 'hidden');
            jQuery('.ui-widget-overlay').css('width', '100%');
        }).bind("dialogclose", function (event, ui) {
            // fix for width:auto in IE
            jQuery(this).parent().css("width", "auto");

            // fix for scrollbars in IE
            jQuery('body').css('overflow', 'auto');
        });
    }

    $dialog.dialog("option", "buttons", {
        "بستن": function () {
            afterDialogClose(aftercompleteUrl, aftercompleteTargetID);
            $(this).dialog("close");
            $(this).empty();
            $dialog.css('max-height', '');
        }

    });

};

function afterDialogClose(aftercompleteUrl, aftercompleteTargetID) {
    if (aftercompleteUrl != '') {
        $.ajax({
            url: aftercompleteUrl,
            type: 'GET',
            success: function (response) {
                if ($.browser.msie) {
                    //there is a bug in jquery replacewith not working properly
                    $(aftercompleteTargetID).replaceWith(response);
                } else {
                    $(aftercompleteTargetID).replaceWith(response);
                }
            }
        });
    }
}


function loadDialog(tag, event, target, updateList, modal, minWidth) {
    event.preventDefault();
    var $loading = $('<img src="@Url.Content("~/Content/images/ajaxLoading.gif")" alt="loading" class="ui-loading-icon">');
    var $url = $(tag).attr('href');
    var $title = $(tag).attr('title');
    var sgTitle = $(tag).attr('sgtitle');
    if (sgTitle == undefined || sgTitle == '')
        sgTitle = $title;
    if ($(tag).attr('sgtarget') != undefined)
        target = '#' + $(tag).attr('sgtarget');
    var dialog = '';
    if ($(tag).attr('sgdialog') != undefined)
        dialog = '#' + $(tag).attr('sgdialog');
    else
        dialog = '#dialog';

    var formName = "form";
    if ($(tag).attr('sgform') != undefined)
        formName = $(tag).attr('sgform');

    //var $dialog = $('<div></div>');
    var $dialog = $(dialog);
    if (modal == undefined)
        modal = true;
    $dialog.empty();
    $dialog
            .append($loading)
			.load($url, function (response, status, xhr) {
			    if (minWidth == undefined)
			        minWidth = '500px';
			    $dialog.css('min-width', minWidth);
			    $dialog.css('max-width', '850px');
			    $dialog.css('padding', "0");
			    if (xhr.status == 401) {
			        // perform a redirect to the login page since we're no longer authorized
			        RedirectToLoginPage();
			    }
			    else if (xhr.status == 502 || xhr.status == 504) {
			        ShowProxyError(xhr.status);
			    }
			    else if (xhr.status == 200) {
			        $dialog.dialog('open');
			    }
			    else {
			        var o = extraxtError(xhr.responseText);
			        displayError(o, status);
			    }

			})
			.dialog({
			    autoOpen: false
				, title: sgTitle
				, minHeight: 200
				, minWidth: 500
				, width: 'auto'
                , height: 'auto'
				, show: 'fade'
				, hide: 'fade'
                , position: 'center'
                , modal: modal
                , stack: false
                , resize: function (e, ui) {
                    if ($dialog.parent().width() >= parseInt($dialog.css('max-width'), 10)) {
                        $dialog.parent().width($dialog.css('max-width'));
                        $(this).width($dialog.css('max-width'));
                    }
                },
                close: function (e, ui) {
                    $dialog.empty();
                }
			});
    if ($.browser.msie) {
        $dialog.bind("dialogopen", function (event, ui) {
            // fix for width:auto in IE
            var jqDialog = jQuery(this);
            var parent = jqDialog.parent();
            var contentWidth = jqDialog.width();
            parent.find('.ui-dialog-titlebar').each(function () {
                //jQuery(this).width(contentWidth);
            });
            parent.width(contentWidth + 26);
            jqDialog.dialog('option', 'position', 'center');

            // fix for scrollbars in IE
            //jQuery('body').css('overflow', 'hidden');
            jQuery('.ui-widget-overlay').css('width', '100%');
        }).bind("dialogclose", function (event, ui) {
            // fix for width:auto in IE
            jQuery(this).parent().css("width", "auto");

            // fix for scrollbars in IE
            jQuery('body').css('overflow', 'auto');
        });
    }

    $dialog.dialog("option", "buttons", {
        "تایید": function () {
            var dlg = $(this);
            $.ajax({
                url: $url,
                type: 'POST',
                data: $("#" + formName).serialize(),
                success: function (response, textStatus, xhr) {
                    var isValidVal = $('#IsEntityValid', response).val();
                    var isValid = isValidVal == undefined || isValidVal == "True" || response == "";
                    if (!isValid) {
                        $dialog.html(response);
                    }
                    else {
                        if (updateList) {
                            $(target).html(response);
                            $("#ajaxResult").hide().html('اطلاعات ذخیره شد').fadeIn(300, function () {
                                var e = this;
                                setTimeout(function () { $(e).fadeOut(400); }, 2500);
                            });
                        }
                        else {
                            dlg.dialog('close');
                            dlg.empty();
                            alert('اطلاعات ذخیره شد');
                        }
                        dlg.dialog('close');
                        dlg.empty();
                    }
                },
                error: function (xhr, status, error) {
                    if (xhr.status == 401) {
                        // perform a redirect to the login page since we're no longer authorized
                        RedirectToLoginPage();
                    }
                    else if (xhr.status == 502 || xhr.status == 504) {
                        ShowProxyError(xhr.status);
                    }
                    if (xhr.status == 400) {
                        /* display validation errors in edit dialog */
                        var o1 = extraxtError(xhr.responseText);
                        dlg.html(o1, xhr.status);
                    }
                    else {
                        /* display other errors in separate dialog */
                        var o = extraxtError(xhr.responseText);
                        displayError(o, status);
                    }

                }
            });
        },
        "انصراف": function () {
            $(this).dialog("close");
            $(this).empty();
        }

    });

};

function displayError(message, status) {
    var $dialog = $('<div>' + message + '</div>');
    $dialog
				.dialog({
				    //width:600,
				    modal: true,
				    //title: status + ' خطا',
				    title: 'خطا',
				    buttons: {
				        'بستن': function () {
				            $(this).dialog("close");
				        }
				    },
				    close: function (e, ui) {
				        $dialog.empty();
				    }

				});
    if ($.browser.msie) {
        $dialog.bind("dialogopen", function (event, ui) {
            // fix for width:auto in IE
            var jqDialog = jQuery(this);
            var parent = jqDialog.parent();
            var contentWidth = jqDialog.width();
            parent.find('.ui-dialog-titlebar').each(function () {
                jQuery(this).width(contentWidth);
            });
            parent.width(contentWidth + 26);
            jqDialog.dialog('option', 'position', 'center');

            // fix for scrollbars in IE
            //jQuery('body').css('overflow', 'hidden');
            jQuery('.ui-widget-overlay').css('width', '100%');
        }).bind("dialogclose", function (event, ui) {
            // fix for width:auto in IE
            jQuery(this).parent().css("width", "auto");

            // fix for scrollbars in IE
            jQuery('body').css('overflow', 'auto');
        });
    }
    return false;
};

function confirmDialog(message, callback) {
    var $deleteDialog = $('<div>' + message + '</div>');

    $deleteDialog
			.dialog({
			    resizable: false,
			    height: 140,
			    title: "تایید",
			    modal: true,
			    buttons: {
			        "بله": function () {
			            $(this).dialog("close");
			            callback.apply();
			        },
			        "خیر": function () {
			            $(this).dialog("close");
			        }
			    },
			    close: function (e, ui) {
			        $deleteDialog.empty();
			    }
			});
    if ($.browser.msie) {
        $dialog.bind("dialogopen", function (event, ui) {
            // fix for width:auto in IE
            var jqDialog = jQuery(this);
            var parent = jqDialog.parent();
            var contentWidth = jqDialog.width();
            parent.find('.ui-dialog-titlebar').each(function () {
                jQuery(this).width(contentWidth);
            });
            parent.width(contentWidth + 26);
            jqDialog.dialog('option', 'position', 'center');

            // fix for scrollbars in IE
            //jQuery('body').css('overflow', 'hidden');
            jQuery('.ui-widget-overlay').css('width', '100%');
        }).bind("dialogclose", function (event, ui) {
            // fix for width:auto in IE
            jQuery(this).parent().css("width", "auto");

            // fix for scrollbars in IE
            jQuery('body').css('overflow', 'auto');
        });
    }
};

function confirmDelete(message, title, callback) {
    var $deleteDialog = $('<div>' + message + '</div>');
    if (title == undefined)
        title = "حذف اطلاعات";
    $deleteDialog
			.dialog({
			    resizable: false,
			    height: 140,
			    title: title,
			    modal: true,
			    buttons: {
			        "بله": function () {
			            $(this).dialog("close");
			            callback.apply();
			        },
			        "خیر": function () {
			            $(this).dialog("close");
			        }
			    },
			    close: function (e, ui) {
			        $deleteDialog.empty();
			    }

			});
    if ($.browser.msie) {
        $dialog.bind("dialogopen", function (event, ui) {
            // fix for width:auto in IE
            var jqDialog = jQuery(this);
            var parent = jqDialog.parent();
            var contentWidth = jqDialog.width();
            parent.find('.ui-dialog-titlebar').each(function () {
                jQuery(this).width(contentWidth);
            });
            parent.width(contentWidth + 26);
            jqDialog.dialog('option', 'position', 'center');

            // fix for scrollbars in IE
            //jQuery('body').css('overflow', 'hidden');
            jQuery('.ui-widget-overlay').css('width', '100%');
        }).bind("dialogclose", function (event, ui) {
            // fix for width:auto in IE
            jQuery(this).parent().css("width", "auto");

            // fix for scrollbars in IE
            jQuery('body').css('overflow', 'auto');
        });
    }
};

function deleteRow($btn, target) {
    $.ajax({
        url: $btn.attr('href'),
        //type: 'POST',
        success: function (response) {
            $(target).html(response);
            //                $("#ajaxResult").hide().html(response).fadeIn(300, function () {
            //                    var e = this;
            //                    setTimeout(function () { $(e).fadeOut(400); }, 2500);
            //                });
        },
        error: function (xhr) {
            if (xhr.status == 401) {
                // perform a redirect to the login page since we're no longer authorized
                RedirectToLoginPage();
            }
            else if (xhr.status == 502 || xhr.status == 504) {
                ShowProxyError(xhr.status);
            }
            else {
                /* display errors in separate dialog */
                var o = extraxtError(xhr.responseText);
                displayError(o, status);
            }
        }
    });
    return false;
};

function doAction($btn, target) {
    $.ajax({
        url: $btn.attr('href'),
        //type: 'POST',
        success: function (response) {
            $(target).html(response);
            //                $("#ajaxResult").hide().html(response).fadeIn(300, function () {
            //                    var e = this;
            //                    setTimeout(function () { $(e).fadeOut(400); }, 2500);
            //                });
        },
        error: function (xhr) {
            if (xhr.status == 401) {
                // perform a redirect to the login page since we're no longer authorized
                RedirectToLoginPage();
            }
            else if (xhr.status == 502 || xhr.status == 504) {
                ShowProxyError(xhr.status);
            }
            else {

                /* display errors in separate dialog */
                var o = extraxtError(xhr.responseText);
                displayError(o, status);
            }
        }
    });
    return false;
};


function extraxtError(error) {

    start = error.search("<title>") + 7;
    end = error.search("</title>");
    if (start > 0 && end > 0)
        return "" + error.substring(start, end) + "";
    else
        return "خطا";

    var d = $(error);
    var o = "";
    $('*', d).each(function () {
        o = o + $(this).html() + " ";
    });
    return o;

}

function ShowProxyError(status) {
    alert("خطای " + status + ": پراکسی تنظیم شده در مرورگر، درخواست شما را رد کرده‌است");
}

function handleAjaxFormFailure(xhr) {
    if (xhr.status == 502 || xhr.status == 504) {
        ShowProxyError(xhr.status);
    }
    else {
        var o = extraxtError(xhr.responseText);
        displayError(o, status);
    }
} 

