//бэкап аякс.жс лежит в корне
function Ajax(){
    var ajaxCount = 0;
    var maxAjaxCount = 5;
    var oldUrl = new Array();
    this.cache = new AjaxCache();
    
    this.incAjaxCount = function(){
        if(ajaxCount >= maxAjaxCount){
            alert('на данный момент выполняется максимальное число запросов, подождите несколько секунд!!!');
            return false;
        }
        ajaxCount++;
        API.showLoading();
        return true;
    }
    
    this.decAjaxCount = function(){
        ajaxCount--;
        if(ajaxCount==0)
           API.hideLoading();
    }
    
    this.checkRightError = function(p){
        if(typeof(p.rightError) != 'undefined'){
    		if(p.rightError==1){
    			API.showWindow({'title':p.title,'content':p.content,'modal':true});
    			return false;
    		}
    	}
    	return true;
    }
    
    this.AjaxRequest = function(p){
         
         if(typeof(p) == 'undefined') throw ("ничего не передано в аякс");
         if(typeof(p.data) != 'undefined') p_data = p.data;
         else p_data = '';
         if(typeof(p.url) == 'undefined') throw("url - обязательный параметр");
         if(!ajax.incAjaxCount()) return false;     
         return jQuery.ajax({
    		type: 'POST',
    		dataType: 'json',
    		url: p.url,
    		data: p_data,
    		success: function(data){
    		   ajax.decAjaxCount();
    		   if(!ajax.checkRightError(data)) return false;
    		   if(data.status==1){
	    	    
    			    if (typeof p.callback != "undefined") 
    			         p.callback(data);
    			}else
    			 API.showWindow({'title':"error",'content':data.message,'modal':true});
    		},
    		error: function(data){
    			ajax.decAjaxCount();
    			if(data.responseText)
     		    	API.showWindow({'title':"error",'content':data.responseText,'modal':true});
    		}
    	}); 
    }
    
    this.AjaxContentRequest = function(p){
         if(typeof(p) == 'undefined') throw ("ничего не передано в аякс");
         if(typeof(p.data) != 'undefined') p_data = p.data;
         else p_data = '';
         if(typeof(p.url) == 'undefined') throw("url - обязательный параметр");
         
         if(tmp = ajax.cache.get(p.url)){ //проверяем есть ли кэш
             ajax.addContentToTarget(p.target,tmp.data,p.callback);
    		 return;
         }
         
         if(!ajax.incAjaxCount()) return false;     
         jQuery.ajax({
    		type: 'POST',
    		dataType: 'json',
    		url: p.url,
    		data: p_data,
    		success: function(data){
    		   ajax.decAjaxCount();
	    	    if(!ajax.checkRightError(data)) return false;
    			if(data.status==1){
    			   target = (typeof p.target == "undefined")?data.target:p.target;
    			   data.ajaxGo = p;
    			   if((typeof p.cache != "undefined" && p.cache == 'true') || 
    			      (typeof data.cache != "undefined" && data.cache == 'true'))
	                  ajax.cache.add(p.url,data,target);
	               
	               ajax.addContentToTarget(target,data,p.callback);
    			    //window.location.reload();
    			}
    			else
    			  API.showWindow({'title':"error",'content':data.message,'modal':true});
    			 //outputMessage(data.message,jQuery("#salaryMessageOutput"),0);
    		},
    		error: function(data){
    		    ajax.decAjaxCount();
     		    API.showWindow({'title':"error",'content':data.responseText,'modal':true});
    		}
    	});
    }
    
    this.addContentToTarget = function(target,data,callback){ //функция добавляет контент после аякса
        target2 = jQuery(target).empty();
	    jQuery('<div>'+data.content+'</div>').appendTo(target);  
		
	    if(typeof $(this).scrollTo == "function" && data.ajaxGo.scrollTo == true){
	    	$(window).scrollTo("#menu", 300);
	    }
	    switch (typeof callback) {	
	        case 'function':
	           callback(data);
	           break;
	        case 'undefined':
	           //break;
	        default:
	           //console.log("ПОКА НЕ ПОНЯТНО КАК ЭТО ОБРАБОТАТЬ");
	           break;
	    }	    
	    
	    API.afterLoad();
    }
    
    this.go = function(obj,data){
        switch (obj.tagName) {
          case 'A':
            url = obj.attributes.href.nodeValue; //надо делать проверку на плохие сслыки
			break;
		case 'IMG':
			url = obj.attributes.longdesc.nodeValue;
			break;
		case 'FORM':
			url = obj.attributes.action.nodeValue +'?' + $(obj).serialize();
			break;
          default:
            return false;
        }
        try {
         
          oldUrl[curLoc]=true;
          curLoc = url;
          history.pushState({}, '', url);
	      if(getURL() != url){ //костыль для сафари не будет работать аякс
            window.location.pathname = url;
            return;
          }
         
        } catch(e) {
            
            return; //пока не придумали как четко сделать то в браузерах где не работает pushState буде тупо ссылке переходить
        }
        if(typeof data.CR == "undefined") data.CR = true;
        if(typeof data.cache == "undefined") data.cache = true;
		if(typeof data.scrollTo == "undefined") data.scrollTo = true;
        
        //ajaxData = {}
        //ajaxData.url = url;
        //ajaxData.data = data;
        data.url = url;
        if(typeof data.CR!= "undefined"){ //ContentRequest
            //ajaxData.target = data.target;
          
            ajax.AjaxContentRequest(data);
        }
        return false;
    }
	
	function getURL(){
		return window.location.pathname+window.location.search;
	}
    
	this.getURL = getURL;
	
    var lazy = 'не поленись и исправь код, где увидел эту ошибку!!!';
    this.AjaxGetAndShow = function(){
        alert("ВНИМАНИЕ!!! Эта функция больше не поддерживается!!!!!GetAndShow"+lazy)
    }
    
    this.AjaxAddRequest = function(){
        alert("ВНИМАНИЕ!!! Эта функция больше не поддерживается!!!!AjaxAddRequest!"+lazy)
    }
    
    this.showAjaxContent = function(){
        alert("ВНИМАНИЕ!!! Эта функция больше не поддерживается!!!!! вместо нее нужно использовать API.showWindow()!!"+lazy);
    }
    this.ajaxWindowClose = function(){
        alert("ВНИМАНИЕ!!! Эта функция больше не поддерживается!!!!! вместо нее нужно использовать API.windowClose(id)!!"+lazy);
    }
    
    
    
}

var ajax = new Ajax();
//var curLoc = window.location.pathname;
var curLoc = ajax.getURL();

var myLocChange = false;

var urlCheckerIntervalID = setInterval(locChecker,200)

function locChecker() {
    //loc = window.location.pathname;
	loc = ajax.getURL();
    //var loc2 = window.location.pathname;
    //var loc = oldLoc;
    
    if (loc != curLoc) {
      if ($.browser.msie6) {
         location.reload(true);
      } else {
        if(tmp = ajax.cache.get(loc)){ //проверяем есть ли кэш
           
             ajax.addContentToTarget(tmp.target,tmp.data);
    		 //return;
        }else{
            
            ajax.AjaxContentRequest({
                url : loc
            })
        }
        curLoc = loc;
      }
    }
}
