
var requestController = {

	progressDiv: null,
	
	inProgress: false,
	
	currentRequest: null,
	
	queue: [],
	
	logger: function(msg){
		
		alert(msg);
		
	},
			
	mode: 'queue',	
	
	getProgressDiv: function(){
	
		if (!this.progressDiv){
		
			this.progressDiv = document.getElementById('progressDiv');
		
			if (!this.progressDiv&&document&&document.body){
			
				this.progressDiv = document.createElement('DIV');	
				this.progressDiv.style.position = 'absolute';
				this.progressDiv.style.display = 'none';
				this.progressDiv.style.backgroundColor = 'red';
				this.progressDiv.style.color = 'white';
				this.progressDiv.style.padding = '5px';
				this.progressDiv.style.left = '90%';
				this.progressDiv.style.top = '1px';
				this.progressDiv.style.width = '10%';
				this.progressDiv.style.zIndex = 100000;

				document.body.appendChild(this.progressDiv);
			}
							
		}
		
		return this.progressDiv;
	
	},
	
	showProgress: function(message){
	
		var d = this.getProgressDiv();		
		d.innerHTML = message;
		d.style.display = '';
	
	},
	
	hideProgress: function(message){
			
		this.progressDiv.style.display = 'none';
	
	},
	
	makeGetRequest: function(url,func,random){
		
		var q = {};
		q.url = url;
		q.func = func;
		q.method = "GET";
		q.random = random;
		this.queue.push(q);	
		this.next();
	
	},
	
	makePostRequest: function(url,data,func){
		
		this.makeBasicPostRequest(url,data,func,false);
		
	},
	
	makeUrgentPostRequest: function(){
		
		this.makeBasicPostRequest(url,data,func,true);
		
	},
	
	makeBasicPostRequest: function(url,data,func,urgent){						
		
		if (data && typeof(data)!='string') {
		
			var res = "";
			
			if (typeof(data)=='array'||(typeof(data)=='object')) {
																		
				for (var i in data){
						
					if (res != "") res +="&";
						
					res += i + "=" + encodeURIComponent(data[i]);
						
				}												
				
				data = res;
				
			} else {
				
				data = false;
				
			}
			
		}
		
		var q = {};
		q.url = url;
		q.func = func;
		q.method = "POST";
		q.data = data;
		q.random = true;
		
		if (urgent) this.queue.unshift(q);	
		else this.queue.push(q);
			
		this.next();
				
	},				
	
	buildRequest: function(){
						
		//setRequestHeader("If-Modified-Since", "Tue, 1 Jan 1980 00:00:00 GMT");		
		var req = null;	
		if (window.XMLHttpRequest) {		
			req = new XMLHttpRequest();
			if (req.overrideMimeType) req.overrideMimeType('text/html');						
		} else if (window.ActiveXObject) { // IE		
			req = new ActiveXObject("Msxml2.XMLHTTP");			
		}
		
		if (!req) {
		
			this.logger("Can't create XMLHTTP request");
			return false;
		
		}

		return req;			
	},
	
	requestOnChange: function(req,func){
								
		if(req.readyState==4) {

			this.showProgress("+а_рузка...");		
			
			var result = null;
			result = {error:false, data:req.responseText};
			/*if (req.status==200){ // 200 means "OK"										
															 				 																					
					result = {error:false, data:req.responseText};
																																																													
			} else {
						
				this.logger("Return status is not 200 " + req.status);
				result = {error:true, errorCode:"responceResultError", errorMessage:"STATUS_CODE " + req.status};
			
			}*/ 
			

			this.hideProgress();
					
			try {
										
				if(func) func(result);
				
			} catch(ex){
			
				this.logger("error in callback function " + ex);
			
			}	
			
			this.inProgress = false;
			
		 	this.next();												
		 	
		}
				
	},

	next: function(){
			
		if (!this.inProgress) {
		
			this.inProgress = true;
								
			this.showProgress('+а_рузка...');		
				
			var req = this.buildRequest();
						
			if (!req) {		
			
				alert("can't initialize XMLHttpRequest")	
				this.hideProgress();
				this.inProgress = false;				
				return false;				
			
			}	
			
			this.currentRequest = this.queue.shift();
						
			if (!this.currentRequest) {
			
				this.hideProgress();
				this.inProgress = false;
				return false;
				
			}
							 	
	 		try {
	 	
	 			if (this.currentRequest.func) {
	 				
	 				var func = this.currentRequest.func;
	 				
	 				req.onreadystatechange = function(){requestController.requestOnChange(req,func);};
	 				
	 			}	
							
				if (this.currentRequest) {
					
					this.currentRequest.url = util.urlParamReplace(this.currentRequest.url,'r',new Date().getTime());	
					
				}											
																				
				req.open(this.currentRequest.method, this.currentRequest.url, true);				
				
				if (this.currentRequest.method=='POST'){

					req.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");					
					req.send(this.currentRequest.data);					
					
				} else {
	
					req.send('');	
					
				}		 
																																																																																			
				return true;
			
		 	} catch(ex) {
		 		 
		 		this.logger(ex);
		 		
		 		if (this.currentRequest&&this.currentRequest.func){		 			
		 			
		 			this.currentRequest.func({error:true,errorCode:"requestError",errorMessage:ex});		 			
		 			
		 		}		 		 
		 		
		 		this.inProgress = false;		 		
		 		return false;	
		 		 			 	
		 	}
		         
		} 
	
	}			
					
};

var util = {	
	
	urlParamReplace: function(url,param_name,param_value){
						
			url = new String(url);						

			if (url.indexOf("&"+param_name+"=")!=-1||url.indexOf("?"+param_name+"=")!=-1) {  
			
				var pattern = param_name + '\\=[^\\&]*';
				var replace = "";
							
				if (param_value!='') {				
						replace=param_name+"="+encodeURIComponent(param_value); 									
						url = url.replace(eval(new String('/([&?])'+pattern+'/').toString()),'$1'+replace);
				} else {
						replace=''; 			
						url = url.replace(eval(new String('/[?]'+pattern+'\\&/').toString()),'?'+replace);
						url = url.replace(eval(new String('/[&?]'+pattern+'/').toString()),replace);	
				}		
				
			} else if (param_value!='') {
							
				if (url.indexOf('?')==-1)
					url = url + "?";
				else 	
					url = url + "&";
					
				url = url + param_name + "=" +encodeURIComponent(param_value); 									
				
			}

			return url;					
	},
		
	log: function (msg) {
	
		if (document&&document.body){
			var d = document.createElement("DIV");
			d.style.position = 'absolute';
			d.style.top = (coordinatesController.y + Math.round(Math.random()*100)) + 'px';
			d.style.left = (coordinatesController.x + Math.round(Math.random()*100)) + 'px';
			d.style.border = "1px solid black";
			d.style.padding = "3px";
			d.style.backgroundColor = '#FFFFFF';
			d.innerHTML= msg;		
			d.style.zIndex = 80000;		
			document.body.appendChild(d);				
			window.setTimeout(function(){util.detachElement(d);},3000);
		} else {
		
			alert("LOG: " + msg);
		
		}				
	
	},

	msg: function (msg) {

		var color = arguments[1] ? arguments[1] : "#000000";
	
		if (document&&document.body){
			var d = document.createElement("DIV");
			d.style.position = 'absolute';
			d.style.top = coordinatesController.y + 15 + 'px';
			d.style.left = coordinatesController.x - 5 + 'px';
			d.style.border = "1px solid #CCCCCC";
			d.style.color = color;
			d.style.padding = "5px";
			d.style.backgroundColor = '#FFFFFF';
			d.innerHTML= "&nbsp;"+msg+"&nbsp;";
			d.style.zIndex = 80000;		
			document.body.appendChild(d);				
			window.setTimeout(function(){ util.detachElement(d); delete d; },1500);
		}
	
	},
	
	getElementFromText: function(text,element_tag){
	
		d = document.createElement("DIV");
		d.innerHTML = text;
		d = this.getFirstChild(d,element_tag);
		if (!d) return null;
		util.detachElement(d);		
		return d;
		
	},
			
	createCookie: function (name,value,days){        
	
		if (days){
		
			var date = new Date();
			date.setTime(date.getTime()+Math.round(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
			
		}else var expires = "";
		
		document.cookie = name+"="+encodeURIComponent(value)+expires+"; path=/";
	},

	readCookie: function (name){
	
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		
		for(var i=0;i < ca.length;i++){
		
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		
		return null;
	},

	eraseCookie: function (name){
	
		this.createCookie(name,"",-1);
		
	},
		
	
	getLastChild : function(obj,tagname){
													
		obj = obj.lastChild;		

		if (obj&&obj.nodeName != tagname)		
			return util.getPreviousSibling(obj,tagname);	
		
		return obj;																				
		
	},
			
	focusFirstVisibleControl : function(obj_id){
		
		try {

		var obj = obj_id;
						
		if (typeof(obj_id) == 'string') obj = document.getElementById(obj_id);
		
		if (obj&&obj.nodeName!="FORM"){
		
			var forms = obj.getElementsByTagName("FORM");
			if (forms.length == 0) return false;
			obj = forms[0];
		}		
	
		if (obj&&obj.nodeName=="FORM")	{																
										
			for (var i=0; i<obj.elements.length; i++) 
				if (
					obj.elements[i].type!="button"&&
					obj.elements[i].type!="reset"&&
					obj.elements[i].type!="submit"&&
					obj.elements[i].type!="select-one"&&
					obj.elements[i].type!="hidden"
					){							
						obj.elements[i].focus();
						break;
					
					}			
					
		}			
					
		} catch(ex){
		
			alert(ex);
		}			
			
	},
	
	getFirstChild : function(obj,tagname){

		obj = obj.firstChild;		

		if (obj&&obj.nodeName != tagname)		
			return util.getNextSibling(obj,tagname);

		return obj;

	},
		
	getNextSibling : function(obj,tagname){
		
		obj = obj.nextSibling;
		
		while (obj&&(obj.nodeName!=tagname))
			obj = obj.nextSibling; 
			
		return obj;				
	},
	
	isParent : function(obj,parent) {
	
		if (!parent) return false;
					
		while(obj&&obj.nodeName!="BODY"){
		
			if (obj.parentNode==parent) return true;		
			obj = obj.parentNode;
			
		}
	
		return false;
	},

	getPreviousSibling : function(obj,tagname){

		obj = obj.previousSibling;		

		while (obj&&(obj.nodeName!=tagname))
			obj = obj.previousSibling; 
			
		return obj;						
	},

	
	getParent : function(obj,tagname){
	
		obj = obj.parentNode;
		return this.getElement(obj,tagname);
		
	},
	
	getElement : function(obj,tagname){
	
		while (obj&&(obj.nodeName!=tagname))
			obj = obj.parentNode;
		
		return obj;
	
	},
	
	detachElement : function(obj){
		
		if (obj&&obj.parentNode){ obj.parentNode.removeChild(obj)};
	
	},
	
	getEventTarget : function(e){
	
		if (!e) e = window.event;
		
       		if (e.target) {

			if (e.target.nodeType == 3) e.target = e.target.parentNode;
        	 	return e.target;
        	 
      		} else if (e.srcElement)

        	return e.srcElement;
	
   	},
   
   	findPos : function(obj) {

		var r = {x:0,y:0};

		if (obj.offsetParent) {
		
			while (obj.offsetParent) {
				r.y += obj.offsetTop;
				r.x += obj.offsetLeft;
				obj = obj.offsetParent;
			}
			
		} else {
			if (obj.x) r.x += obj.x;
			if (obj.y) r.y += obj.y;
		}

		return r;

	},
					
	showElement : function(obj){

		if (obj) obj.style.display = '';
		  
	},
	
	hideElement : function(obj){

		if (obj) obj.style.display = 'none';		
	
	},
	
	replaceElement : function(src,dst){
	
		if (src&&dst){
	
			util.detachElement(dst);
			src.parentNode.insertBefore(dst,src);	
			util.detachElement(src);
			
		}
	
	},
	
	makeDate: function(days,time){
						
		var d = new Date(new Date().getTime()+ days*24*60*60*1000);		
		 
		var month = d.getMonth()+1;
		var day = d.getDate();

		if (month < 10) month = "0"+month;
		if (day < 10) day = "0"+day;
	
		var res = d.getFullYear() + "-" + month + "-" + day;

		if (time) res = res + " " + time;		
		
		return res;
	}	
	
};

var coordinatesController = {    

	x : 0,
	y : 0,
	lastX : 0,
	lastY : 0,
	deltaX: 0,
	deltaY: 0,
	left: false,
	up: false,
	handlers : [] ,	
	
	init: function(){
						
		if (!document.all) document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove = this.getMouseXYInterface;
						
	},	
	
	getMouseXYInterface: function(e){
	
		return coordinatesController.getMouseXY(e);
	
	},

	getMouseXY: function(e){
	
		if (!e) var e = window.event;
	
		if (e.pageX || e.pageY) {
		
				this.x = e.pageX;
				this.y = e.pageY;
				
		}  else if (e.clientX || e.clientY) {
		
			this.x = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			this.y = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}

  		if (this.x < 0) {this.x = 0;}
		if (this.y < 0) {this.y = 0;}  
		
		this.left = false;
		this.up = false;
		this.deltaX = this.x - this.lastX;
		this.deltaY = this.y - this.lastY;
		
		if (this.deltaX < 0) this.left = true;
		if (this.deltaY < 0) this.up = true;				
									
		this.lastX = this.x;
		this.lastY = this.y;
  		  				
		for (var i in this.handlers)
			this.handlers[i](e,this.x,this.y,this.left,this.up);	
			
  		return true;
	},

	addHandler: function(_handler){
		
		this.handlers.push(_handler);	
				
	}						 

};

coordinatesController.init();

