/*----------------------показывает загрузку----------------------------------*/


    //показывает загрузку    
  $(document).ready(function() { 
  $.ajaxSetup({ cache: true });      
  $('body').ajaxStart(function()
  {
    $(this).prepend('<div id = "load" style="z-index: 9999; top: 200px; position: fixed; margin-left: auto;  margin-right: auto;background-color: #000; height: 70px;width: 205px; border-radius: 15px;"><p style="font-size: 10pt; position: absolute; top: 10px;left: 40px;color: #fff; ">Идёт загрузка...</p><img src = "/img/load.gif" style="display: block; position: absolute; top: 30px; left: 75px; " /></div>'); 
    var winWidth = $(window).width();
    var elemWidth = $('#load').css('width');
    var elemWidth = elemWidth.substring(0, elemWidth.length - 2);
    var left = (winWidth - elemWidth)/2;  
    $('#load').css('opacity', '0.8').css('left',left ); 
  } );
  $('body').ajaxStop(function()
    {
     $('#load').remove();
    } ); 
}); 

/*---------------------объект для хранения переменных - создаём один раз на всё приложение------------------------------*/

   function sm_varRegistry()
   {
             
          //здесь храним переменные
        this.vars = new Array(); 
         
          //записываем пременные
        this.set = function(name, val)
        {
        
           if(this.vars[name] == undefined)
           {
        
              this.vars[name] = val;
          
           }
           else
           {
        
              alert('Переменная с именем '+name+' уже находится в регистре - задайте другое имя');
        
            }
        
    
        }
        
           //извлекаем переменную
        this.get = function getVar(name)
        {
    
           if(this.vars[name] != undefined)
           {
       
              return this.vars[name];
       
           }
    
           return false;
      
        }
        
           //удаляем переменную
        this.unset = function(name)
        {
        
           delete this.vars[name];
        
        }
        
   }
   
   sm_registry = new sm_varRegistry(); 
   
   
   /*--------------------------------------затемнённый экран---------------------------------------------------*/   
   
      //создаёт затемнённый экран
        function blackWin(elemId)
        {
        
             this.id=elemId;
        
            if(document.getElementById('sm_black_window') != undefined )
            {
               $('#sm_black_window, #sm_black_window_cont').remove();
              
            }
            
                //создаём контейнер для формы     
             $("body").prepend('<div id="sm_black_window" style="position:absolute; background-color:#000; display:none; z-index:100;"></div><div id="sm_black_window_cont" style="display:none; position:absolute; z-index:101; cursor:pointer;"><div id="'+elemId+'" style="margin-left:auto;margin-right:auto; cursor:default;"></div></div>'); 
            
             $("#"+elemId).css('margin-top',($(document).scrollTop()+150 )+'px' ); 
            
        }
    
          //показывает затемнённый экран
        blackWin.prototype.show = function()
        {
            if(document.getElementById('sm_black_window') != undefined)
            {
                    //отоброжаем форму
                 $("#sm_black_window").css("opacity", '0.6').css('height', $(document).height() ).css('width', screen.width ).fadeIn(700);
                 $('#sm_black_window_cont').css('height', $(document).height() ).css('width', screen.width ).fadeIn(700);         
                 $("#sm_black_window_cont").click(function(){
              
                    
                    $('#sm_black_window_cont, #sm_black_window').fadeOut(500, function(){
                    
                         $('#sm_black_window_cont, #sm_black_window').remove();
                    }); 
                     
                     
                   
                 });
                 $("#"+this.id).click(function(e){ 
                    if(e.stopPropagation) e.stopPropagation();
                   else e.cancelBubble = true;
                 });
            }
        }   
        
/*-------------------------------------объект для работы с сообщениями-------------------------------------------*/  
         
    //конструктор
  function sm_custMess(type,text)
  {
   
        //тип сообщения
     this.type = type;
     
        //текст сообщения
     this.text = text;
     
     if(this.type == 1)
    {
        
      var id = "mess_change";
      var self = this;
   
      if(document.getElementById(id) != undefined)
         {  
          var jqId = $('#mess_change');                             
          jqId.remove();
         } 
      
         
      $("body").prepend('<div id="mess_change"><span class="mess_text">Сообщение: '+this.text+'</span><a class="close" href="#">X</a></div>');
      var jqId = $('#mess_change');   
      if($.browser.msie && $.browser.version == '6.0')
       {                                                    
       jqId.css('top',$(document).scrollTop() );
       }
      jqId.css("opacity", '0.8');
      $('#'+id+" a.close").click(function(){self.hide(); return false;});
      setTimeout(function(){self.hide()}, 5000); 
    
    }
    else if(this.type == 2)                    
    {
       
      $("body").prepend('<div id = "sm_mess_cont" style="position:absolute;"><div id="student_succefull"><span class="mess_text">'+this.text+'</span><div id="buttons_add_st"><a class="mess_butt_ok" href="#">Да</a> &nbsp;<a class="close_m_student close" href="#">Нет</a></div></div></div>');
      $("#sm_mess_cont").css('height', $(document).height() ).css('width', screen.width );  
      var id = "student_succefull";
      var jqId = $('#student_succefull'); 
      var nowTop = jqId.css('margin-top');
      var nowTop = nowTop.substring(0, nowTop.length - 2);
      var scroll = $(window).scrollTop();
      var top    = parseFloat(nowTop)+parseFloat(scroll); 
      var winWidth = $(window).width();  
      var elemWidth = jqId.css('width');
      var elemWidth = elemWidth.substring(0, elemWidth.length - 2);
      var scrollLeft = $(window).scrollLeft();
      var left = ( (winWidth - elemWidth)/2) + scrollLeft; 
      jqId.css('opacity', '0.8').css('margin-top', top+'px').css('margin-left', left+'px');
      var self = this; 
      $('#'+id+" a.close").click(function(){self.hide(); return false;});     
    }                
   
    this.id = id; 
     
              
  }
  
    //удаляем сообщение 
  sm_custMess.prototype.hide = function()
  {    
     
     var jqId = $('#'+this.id);
                   
     if(this.type == 2)
     {                                                                
      jqId.fadeOut('700');
      setTimeout(function(){jqId.remove(); $("#sm_mess_cont").remove();}, 750);
     }
     else
     {                                                                    
      jqId.fadeOut('700');
      setTimeout(function(){jqId.remove();}, 750);
     }
                 
  }
   
          
/*-------------------------------logout-----------------------------------------------*/    

function logout()
{
    $.get("/ajax/logout.php", function(data){
       if(data == 1)
       {
           sm_registry.unset('login');
           $('#logout').css('display', 'none');
           $('#login').css('display', 'inline');
       }
    });

}    


/*--------------------------------Функция убирает пробелы------------------------------------*/

// Убирает пробельные символы слева
function ltrim(str) {
    var ptrn = /\s*((\S+\s*)*)/;
    return str.replace(ptrn, "$1");
}
// Убирает пробельные символы справа
function rtrim(str) {
    var ptrn = /((\s*\S+)*)\s*/;
    return str.replace(ptrn, "$1");
}
// Убирает пробельные символы с обоих концов
function trim(str) {
    return ltrim(rtrim(str) );
}


/*---------------------------dump - отладочная функция-----------------------------------*/
  function dump(obj) {
    var out = "";
    if(obj && typeof(obj) == "object"){
        for (var i in obj) {
            out += i + ": " + obj[i] + "\n";
        }
    } else {
        out = obj;
    }
    alert(out);
} 

/*--------------------------------Cookies----------------------------------------------------*/

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset)
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    return(setStr);
}

function unsetCookie(cookie_name){
  var cookie_date = new Date (); 
    cookie_date.setTime (cookie_date.getTime() - 1);
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

/*----------------------------Действие, которое пользователь хотел совершить до авторизации---------------------------------*/


function loginActions()
{
    var action = getCookie('logAct');
    unsetCookie('logAct');
    
    if(action)
    {
      action +='()';
      eval(action);
    }
}  
