var FE       = new FE_F;

//Для обработки событий
function customHandler(desc,page,line,chr)  {
  var errorsDiv = getId('debugErrors');

  //prepare error
  var errId     = FE.errList.push({'message':'<b>JAVASCRIPT '+desc+'</b><br/>'+page+'('+line+') '+(chr?':'+chr:''),'state':0})-1;
  if (errorsDiv){
    var callstackText = '';
    FE.errList[errId].state = 1;
    msg = msg.split('([').join('<br/>([');
    msg = msg.split('()').join('<br/>');
    var div = document.createElement("DIV");
    div.innerHTML = FE.errList[errId].message+callstackText;
    div.className = 'js';
    errorsDiv.appendChild(div);
    if (getId('ErrorsToggler')) {
      getId('ErrorsToggler').innerHTML = 'Errors '+errorsDiv.childNodes.length;
    }
  }
  return true;
}
window.onerror = customHandler;

var clientW  = 0;
var clientH  = 0;

//события
window.onload = function(event){
  FE.handleEvent('onload',event);
  FE.handleEvent('onafterload',event);
};

window.onresize = function(event){
  FE.handleEvent('onresize',event);
  FE.handleEvent('ajaxonresize',event);
};

FE.manageEvent('onload',"$('body').click(function(event){FE.handleEvent('onmousedown', event, this);})");


document.onmouseup = function(event){
  if(!event){
    event = window.event;
  }
  FE.handleEvent('onmouseup', event);
};

FE.manageEvent('onload',"$.event.add(document, 'keydown', altPresser);$.event.add(document, 'keyup',   altReleaser);");
FE.alt = false;

function altPresser(event){
  if (event.originalEvent.altKey){
    FE.alt = true;
  }
}
function altReleaser(event){
  if (!event.originalEvent.altKey){
    FE.alt = false;
  }
}
//реализация
function FE_F(){
  this.level    = 99999;
  this.loadedExtraFiles = '';
  this.inCompleteFiles = 0;
  this.href     = window.location.href.substr(0,window.location.href.indexOf('index.php'));
  this.errList  = new Array();

  this.clientW  = 0;
  this.clientH  = 0;

  this.handlers = {
  'onload' : new Array(),
  'onresize' : new Array(),
  'ajaxonload' : new Array(),
  'ajaxonresize' : new Array(),
  'ajaxloadcompleted' : new Array(),
  'onmousedown' : new Array(),
  'onmouseup' : new Array()
  };

  //флаг определяет азгрузилась ли страница
  this.loaded = false;

  this.handleEvent = function( evName , event, target){
    msg = '';
    clientW = document.body.clientWidth;
    clientH = document.body.clientHeight;
    this.clientW = clientW;
    this.clientH = clientH;
    for(var i in this.handlers[evName]){
      eval(this.handlers[evName][i]);
    }
    if (evName=='onload'){
      this.handleEvent('onresize');
    }
  }

  //Добавление события
  this.manageEvent = function(evName, toEval){
    msg = '';
    if (this.handlers[evName]==undefined){
      this.addHandler(evName);
    }
    if (!in_array( toEval,  this.handlers[evName], false)){
      this.handlers[evName][toEval] = toEval;
    }
  }

  //Очистка события
  this.clearEvent = function(evName, toEval){
    msg = '';
    if (this.handlers[evName]){
      if (toEval){
        delete this.handlers[evName][toEval];
      }else{
        this.handlers[evName] = new Array();
      }
    }
  }

  //Добавление события
  this.deleteEvent = function(evName, toEval){
    msg = '';
    for(var i in this.handlers[evName]){
      if (this.handlers[evName][i]==toEval){
        this.handlers[evName].splice(i,1);
      }
    }
  }

  //Добавление на лету какого либо файла
  this.loadEFile = function(fileId, filePath){
    //alert(fileId+' '+filePath)
    var ext = filePath.substr(filePath.lastIndexOf('.')+1);
    filePath+='?rnd='+rnd(1, 10000);
    if (ext=='css'){
      this.loadCss(filePath, fileId);
    }
    if (ext=='.js'){
      this.inCompleteFiles++;
      LazyLoad.load(this.href+filePath, function(){this.loadComplete(fileId)}, this, true);
    }
  }

  //Добавление на лету коллекции JSок
  this.loadEFilesJS = function(fileIds, filePaths){
    for (var i in filePaths){
      this.inCompleteFiles++;
    }
    LazyLoad.load(filePaths, function(){this.loadComplete(fileIds)}, this, true);
  }

  this.loadCss = function(filename, fileId){
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", this.href+filename);
    if (typeof fileref!="undefined"){
      document.getElementsByTagName('head')[0].appendChild(fileref);
      this.loadedExtraFiles += 'l'+fileId;
    }

    fileref.onreadystatechange = function () {
      if (fileref.readyState == 'complete') {
        //alert('CSS onreadystatechange fired');
      }
    }
    fileref.onload = function () {
      //alert('CSS onload fired');
    }
  }

  this.loadComplete = function( ids ) {
    res = false;
    if(ids instanceof Array) {
      var res = true;
    } else {
      var res = (ids !== null) && (typeof( ids ) == 'object');
    }
    for (var id in ids){
      this.loadedExtraFiles += 'l'+ids[id];
      this.inCompleteFiles--;
    }
    if (this.inCompleteFiles==0){
      this.handleEvent('ajaxloadcompleted');
      this.clearEvent('ajaxloadcompleted');
    }
  }

  this.addHandler = function(hName){
    this.handlers[hName] = new Array();
  }
}
FE.manageEvent('onload','showAllErrors();');
