/*-----------------------------------------------*/
/*--------Ajax-----------------------------------*/
/*-----------------------------------------------*/

function load_ext(self, url, type, params, completeCallback, callback, onerror, async) {

    async = (async == null) ? true : async;
    return jQuery.ajax({
        url: url,
        type: type,
        dataType: "html",
       // contentType: "application/x-www-form-urlencoded; charset=windows-1251",
        //scriptCharset: "charset=windows-1251",
        data: params,
        async: async,
        error: function(res, textStatus, errorThrown) {
            if (onerror)
                self.each(onerror, [res, textStatus, errorThrown]);
        },
        complete: function(res, status) {
            if(completeCallback)
                self.each(completeCallback, [res.responseText, status, res]);
            // If successful, inject the HTML into all the matched elements
            if (status == "success" || status == "notmodified")
                self.html(res.responseText);

            if (!jQuery.support.scriptEval) {
                jQuery("script", self).each(function() {
                    eval(this.innerText);
                });
            }

            if(callback)
                self.each(callback, [res.responseText, status, res]);
        }
    });
    return self;
}

jQuery.fn.load_post = function(url, params, callback, onerror, completeCallback) {
    var self = this;

    return load_ext(this, url, "POST", params, completeCallback, callback, function(res, textStatus, errorThrown) {
        if (onerror) {
            onerror(res, textStatus, errorThrown);
        }
        else {
            self.html(res.responseText);
        }
    });
};

jQuery.fn.load_post_sync = function(url, params, callback, onerror, completeCallback) {
    var self = this;

    return load_ext(this, url, "POST", params, completeCallback, callback, function(res, textStatus, errorThrown) {
        if (onerror) {
            onerror(res, textStatus, errorThrown);
        }
        else {
            self.html(res.responseText);
        }
    },false);
};

jQuery.fn.load_get = function(url, params, callback, onerror, completeCallback) {
    var self = this;

    return load_ext(this, url, "GET", params, completeCallback, callback, function(res, textStatus, errorThrown) {
        if (onerror) {
            onerror(res, textStatus, errorThrown);
        }
        else {
            self.html(res.responseText);
        }
    });
};


/*-----------------------------------------------*/
/*--------Helpers--------------------------------*/
/*-----------------------------------------------*/

function getAllHeight() {
     var allHight = $("body").height();
     var visibleHeight =  $("html")[0].clientHeight;
     if(visibleHeight > allHight)
         allHight = visibleHeight;
     return allHight;
}

function getVisibleHeight(){
     var visibleHeight =  $("html")[0].clientHeight;
     return visibleHeight;
}

/*-----------------------------------------------*/
/*--------Dialogs--------------------------------*/
/*-----------------------------------------------*/

/*
 * Вызов диалога подтверждения
 */
function confirmDialog(text, accept) {

      var d;
      if($("#system-confirm-dialog").size() == 0)
          d = $("<div id='system-confirm-dialog'/>");
      else
           d = $("#system-confirm-dialog");

      $(d).dialog("destroy");
      $(d).html("<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>"+text);

      $(d).dialog( {
        title: 'Подтверждение операции',
        autoOpen: false,
        resizable: false,
        modal: true,
        show: 'slide',
        hide: 'slide',
        buttons:
            {
                "Нет": function() {
                    $(d).dialog("close");
                },
                "Да": function() {
                   accept($(d));
                }
            }
    });
    $(d).dialog("open");

}

/*
 * Вызов диалога ошибки
 */
function errorDialog(text) {

      var d;
      if($("#system-error-dialog").size() == 0)
          d = $("<div id='system-error-dialog'/>");
      else
           d = $("#system-error-dialog");

      $(d).dialog("destroy");
      $(d).html(text);

      $(d).dialog( {
        title: 'Ошибка!',
        autoOpen: false,
        resizable: false,
        modal: true,
        show: 'slide',
        hide: 'slide',
        buttons:
            {
                "Ok": function() {
                    $(d).dialog("close");
                }
            }
    });

    $(d).dialog("open");
}

/*
 * Вызов диалога ошибки
 */
function statusDialog(text) {

      var d;
      if($("#system-status-dialog").size() == 0)
          d = $("<div id='system-status-dialog'/>");
      else
          d = $("#system-status-dialog");

      $(d).dialog("destroy");


       text =  "<br>" +
               "<div class=ui-widget'>"+
               "   <div class='ui-state-highlight ui-corner-all' style='padding: 0 .7em;background-image:none;background-color: #d2d4ff;'>"+
               "      <p><span class='ui-icon ui-icon-info' style='float: left; margin-right: .3em;'></span>"+
               "          "+text+"</p>"+
               "   </div>"+
               "</div>";

      $(d).html(text);

      $(d).dialog( {
        title: 'Сообщение',
        autoOpen: false,
        resizable: false,
        modal: true,
        show: 'slide',
        hide: 'slide',
        buttons:
            {
                "Ok": function() {
                    $(d).dialog("close");
                }
            }
    });

    $(d).dialog("open");
}



/*
 * Вызов диалога
 */
jQuery.fn.openDialog = function(url, title, width, height, params, success) {

      var d = $(this);

      //если диалог уже где-то существует, то заюзаем его
      var dc = $("#"+$(d).attr("id") +".ui-dialog-content");
      if($(dc).size() > 0) 
          d = dc;
      
      $(d).dialog("destroy");

      var offset = (height - 100)/2 - 10;
      $(d).html("<div style='width:32px; margin-right: auto; margin-left:auto; position:relative;top:"+offset+"px;'>"+
                   "<img src='./css/images/ajax-loader-big.gif'/>"+
                "</div>");
      $(d).dialog( {
            title: title,
            autoOpen: false,
            resizable: false,
            modal: true,
            show: 'slide',
            hide: 'slide',
            width: width,
            height: height,
            open: function(event, ui) {
                $(this).load_post(url,params, function(){ })
            },
            close: function(event, ui) {
                
                if(window.onCloseDialog) {
                     
                     onCloseDialog();
                }
            },
            buttons:
                {
                    "Отмена": function() {
                         $(d).dialog("close");
                    },
                     "Ok": function() {
                         onSaveClick($(d),success);
                    }
                }
          });

          $(d).dialog("open");
}


/*-----------------------------------------------*/
/*--------Validation-----------------------------*/
/*-----------------------------------------------*/

function Validator() {
    this.CheckString = validator_CheckString;
    this.CheckInteger = validator_CheckInteger;
    this.CheckIP = validator_CheckIP;
    this.CheckDate = validator_CheckDate;
    this.CheckRange = validator_CheckRange;

}

/*
 * Проверяет значение на пустоту
 */
function validator_CheckEmpty(value){
    if(value == null || value == "")
        return true;
    return false;
}

/*
 * Проверяет текстовое значение
 */
function validator_CheckString(fieldName,value,maxlength,notEmpty) {
    if(notEmpty && validator_CheckEmpty(value)) {
        errorDialog("Поле '" + fieldName + "'" + " не задано!");
        return false;
    }

    if(validator_CheckEmpty(value))
        return true;

    if(value.length > maxlength) {
        errorDialog("Поле '" + fieldName + "'" + " должно состоять не более чем из "+maxlength+" символов!");
    }

    return true;
}

/*
 * Проверяет числовое целое значение
 */
function validator_CheckInteger(fieldName,value,maxlength,notEmpty) {

    if(validator_CheckString(fieldName,value,maxlength,notEmpty)) {
        var re = /^[0-9]*$/;
        if (!re.test(value)) {
            errorDialog("Поле '" + fieldName + "'" + " должно быть целым числом!");
            return false;
        }

        return true;
    }
    return false;
}

/*
 * Проверяет числовое целое значение на принадлежность диапозону
 */
function validator_CheckRange(fieldName,value,min,max) {

    if(validator_CheckEmpty(value)) {
        errorDialog("Поле '" + fieldName + "'" + " не задано!");
        return false;
    }

    if(validator_CheckInteger(fieldName,value,max.toString(),true)) {
        var temp = parseInt(value);
        if(temp < min || temp > max) {
            errorDialog("Поле '" + fieldName + "'" + " доджно быть в диапазоне от " + min + " до " + max + "!");
            return false;
        }
        return true;
    }
    return false;
}

/*
 * Проверяет ip-адрес
 */
function validator_CheckIP(fieldName,value,notEmpty) {

    if(validator_CheckString(fieldName,value,15,notEmpty)) {
        var re = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
        if (!re.test(value)) {
            errorDialog("Поле '" + fieldName + "'" + " должно быть в формате XXX.XXX.XXX.XXX!");
             return false;
        }
        return true;
    }
    return false;
}

/*
 * Проверяет дату
 */
function validator_CheckDate(fieldName,value,notEmpty) {

    if(notEmpty == false && validator_CheckEmpty(value))
        return true;

    if(validator_CheckString(fieldName,value,10,notEmpty)) {
        var re = new RegExp("[0-9]{2}.[0-9]{2}.[0-9]{4}");
        if (!re.test(value)) {
            errorDialog("Поле '" + fieldName + "'" + " должно быть в формате 'dd.mm.yyyy'!");
            return false;
        }
        return true;
    }
    return false;
}



/*-----------------------------------------------*/
/*--------Sort-----------------------------------*/
/*-----------------------------------------------*/

function IntegerComparer(){
    this.Compare = IntegerComparer_Compare;
}

function IntegerComparer_Compare(a,b) {
    if(isArray(a)) a = a[0];
    if(isArray(b)) b = b[0];

    var v1 = parseInt(a), v2 = parseInt(b);

    if(isNaN(v1)) v1 = null;
    if(isNaN(v2)) v2 = null;
    
    if(v1 == null && v2 == null)
        return 0;
    else if (v1 == null && v2 != null)
        return 1;
    else if (v1 != null && v2 == null)
        return -1;
   
    if(v1 == v2)
        return 0;
    else if (v1 > v2)
        return 1;

    return -1;
}

function SortGrid(table,colindex,comparer, asc) {

    var a = new Array();
    var rows = $("tr",table);
    for(var i = 0; i < $(rows).size(); i++){
        var row = $(rows)[i];
        a[i] = new Array();
        a[i][0] = $("td:nth-child("+colindex+")", row).text();
        a[i][1] = row;
    }

    a.sort(comparer.Compare);
    if(!asc) a.reverse();

    var tbody = $("tbody",table);
    for (i = 0; i < a.length; i++) {
        $(tbody).append(a[i][1]);
    }
}


/*-----------------------------------------------*/
/*--------Extend---------------------------------*/
/*-----------------------------------------------*/

$(function() {
    $.extend($.fn.disableTextSelect = function() {
        return this.each(function() {
            if ($.browser.mozilla) {//Firefox
                $(this).css('MozUserSelect', 'none');
            } else if ($.browser.msie) {//IE
                $(this).bind('selectstart', function() {
                    return false;
                });
            } else {//Opera, etc.
                $(this).mousedown(function() {
                    return false;
                });
            }
        });
    });
    $.extend($.fn.enableTextSelect = function() {
        return this.each(function() {
            if ($.browser.mozilla) {//Firefox
                $(this).css('MozUserSelect', 'text');
            } else if ($.browser.msie) {//IE
                $(this).unbind('selectstart');
            } else {//Opera, etc.
                $(this).mousedown(function() {
                    return true;
                });
            }
        });
    });

    $('.noSelect').disableTextSelect(); //No text selection on elements with a class of 'noSelect'
});



