var requestController = {

	progressDiv: null,
	
	inProgress: false,
	
	currentRequest: null,
	
	queue: [],
	
	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 = '0px';
				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 = "<div style=\"padding:5px;\">" + message + "</div>";
		d.style.display = '';
	
	},
	
	hideProgress: function(message){
			
		this.progressDiv.style.display = 'none';
	
	},
	
	makeGetRequest: function(url,func){
		
		var q = {};
		q.url = url;
		q.func = func;
		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) {
		
			alert("Can't create XMLHTTP request");
			return false;
		
		}
		
		return req;
			
	},
	
	requestOnChange: function(req,func){
								
		if(req.readyState==4) {

			this.showProgress("Готово...");		
			
			var result = null;
			
			if (req.status==200){ // 200 means "OK"										
															 				 
				try {
																					
					result = eval(req.responseText);
					
				} catch(ex) {
				
						alert("Ошибка " + escape(req.responseText));
					
				}
				
													
			} else {
			
				alert("Ошибка сервер вернул " + req.status) + " статус ";
			
			
			}	
			
			this.hideProgress();
				
			if(func) func(result);
			
			this.inProgress = false;
		 	this.next();
												
		}
				
	},

	next: function(){
	
		if (!this.inProgress) {
		
			this.inProgress = true;
								
			this.showProgress('Загрузка...');		
				
			var req = this.buildRequest();
						
			if (!req) {		
			
				alert("Ваш броузер не поддерживает XMLHttpRequest")	
				this.hideProgress();
				this.inProgress = false;
				return false;				
			
			}	
			
			var cur = this.queue.shift();
			
			
			if (!cur) {
			
				this.hideProgress();
				this.inProgress = false;
				return false;
			}
			
	 	
	 		try {
	 	
	 			if (cur.func) {
	 				req.onreadystatechange = function(){requestController.requestOnChange(req,cur.func);};
	 			}	
										
				cur.url = this.urlParamReplace(cur.url,'r',new Date().getTime());	
																				
				req.open('GET', cur.url, true);
								
				req.send('');				
																																
				return true;
			
		 	} catch(ex) {
		 		 
		 		alert(ex); 
		 		this.inProgress = false;
		 		return false;	
		 		 			 	
		 	}
		         
		} 
	
	},
	
	urlParamReplace: function(url,param_name,param_value){
			
			var 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;					
	}			
					
};


cache = {};
sending = false; 


function reloadChilds(obj,childs){

	var f = getParent(obj,"FORM");
		
 	if (f) {
 
		if (obj.nodeName=="SELECT"){
			
			var g = obj.name;
			
			if (!g) g = obj.id;
		
			var i = 0;	
			for(i=0;i < childs.length;i++){
			
				var child = f.elements[childs[i]];
								
				if (child) {				
									
					if (child.nodeName=="SELECT"){
							
							clearSelect(child);	
							addOption(child,"","Загрузка...")
																																																										
					}
													
				}
				
			}
			
			var url=document.location;
						
			url = requestController.urlParamReplace(url,"_mode","reloadChildControls");						
			url = requestController.urlParamReplace(url,"_parent_control",obj.name);			
			url = requestController.urlParamReplace(url,"_parent_control_value",obj.options[obj.selectedIndex].value);
			
			requestController.makeGetRequest(url,function(r){fillSelects(f,r);});
		
		}	
		
	}	
		
}

function getParent(obj,tagname){
	
		obj = obj.parentNode;
		return this.getElement(obj,tagname);
		
}

function fillSelect(sel,arr){
	
	if (sel){
		
		clearSelect(sel);
		addOption(sel,"","  ");	
				
		for(var i in arr){
			addOption(sel,i,arr[i]);	
		}
	
	}
}

function fillSelects(f,data){

	var i,j;

	for (i in data){
	
		if (f.elements[i]){	
						
			if (f.elements[i].nodeName=="SELECT"){
				
					fillSelect(f.elements[i],data[i]);
				
			} 			
											
		} else if ((f.elements[i+"[]"])){
		
				if (f.elements[i+"[]"].nodeName=="SELECT"){
				
					fillSelect(f.elements[i+"[]"],data[i]);
				
				}
		
		}	
	
	}
	
}

function addOption(sel,optionValue,optionText){

	if (sel){
	
		var o = new Option(optionText,optionValue);
					
		if (navigator.userAgent.toLowerCase().indexOf("gecko") != -1)			
			sel.add(o,sel.options[sel.options.length])
		else 
			sel.add(o,sel.options.length);
			 
	}

}
	
function clearSelect(obj){
	
	while (obj.options.length > 0){
		
		obj.remove(0);

	}

}	
	
function getElement(obj,tagname){
	
		while (obj&&(obj.nodeName!=tagname))
			obj = obj.parentNode;
		
		return obj;
	
}

function switchSelectAddText(obj,id){

	if (obj.checked==false) {
	
		var d = document.getElementById(id);
		if (d) d.style.display = '';		
		d.focus();
		
		d = document.getElementById(id+"_add");
		if (d) {
			d.value = "";
			d.style.display = 'none';				
		}	
		
	} else {
	
	
		var d = document.getElementById(id+"_add");
		if (d) d.style.display = '';		
		d.focus();
		
		d = document.getElementById(id);
		if (d) {
			d.value = "";
			d.style.display = 'none';		
			d.selectedIndex = 0;				
		}
	
	
	}	

}

function deleteImage(id,controlName){
	
	var a = document.getElementById("image_"+id);
	if (a) a.parentNode.removeChild(a);	
	delete a;
	a = document.getElementById(controlName+"_image_select_div");
	
	if (a) {
		a.style.display = 'block';		 		 
	}	
	
	a = document.getElementById(controlName);
	
	if (a){
		
		if (a.value.indexOf(",")==-1){
			a.value = "";
		} else {
			
			var b = a.value.split(1);			
			a.value = "";
			
			for (var i=0; i <  a.length; i++){
				
				if (b[i]!=id){
					
					if (a.value!="") a.value += ",";
					a.value += b[i];
					
				}
				
			}
			
		}	
		 
	}	 
	
}	

function addImage(obj){
	
	var a = obj.parentNode;
	
	if (a){
		
		var b = a.cloneNode(true);
		a.parentNode.insertBefore(b,a.nextSibling);
		obj.style.display = 'none';
		
	}
		
}
