var parentControlValueId;


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(){
										
		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("Error " + escape(req.responseText));
					
				}
				
													
			} else {
			
				alert("Error server return " + req.status) + " 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("Your browser don't support 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, type_id){

	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,"","Загрузка...")
																																																										
					}
													
				}
				
			}
			//window.alert('1');
			var url = '';
			if (typeof(popupController) != 'undefined') {
			var lastOpenPopup = popupController.getLastPopup();
			//window.alert('2');
			
			if (lastOpenPopup == null) {				
				url = s3.lastContentUrl;
			} else {
				url = lastOpenPopup.url;
			}
			}
			
			if (!url) url = document.location;	
			
			//window.alert(url);
			url = (url+'').replace('#', '');
			//window.alert(url);		
						
			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);
			//type_id = 39;
			if (type_id > 0)
				url = requestController.urlParamReplace(url,"type_id",type_id);
			
			//window.alert(url);
			
			//parent control value for autocomplete
			
			parentControlValueId = obj.options[obj.selectedIndex].value;


			var __func = function(r){//console.log(r);window.alert('bbb1');
				fillSelects(f,r);
				fillCheckboxes(r);
				//if (function_exists('set_variants_groups')) set_variants_groups();
				var i;
				for (i in r) {reparseCheckboxes(i+'_selectcheckbox_container');}
				for (i in r){reparseSelect(i);}
			};	
			
			requestController.makeGetRequest(url,__func);
		
		}	
		
	}	
		
}

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 fillCheckboxes(data) {
	var i, element, html;
	for (i in data) {
		var container = document.getElementById(i+'_selectcheckbox_container');
		if (container != null) {
			html = '';
			for (element in data[i]) {
				//html += '<b>1</b>';
				html += '<div><input type="checkbox" id="'+i+'" name="'+i+'[]" value="'+element+'" /> '+data[i][element]+'</div>';
			}
			container.innerHTML = html;
		}
	}
}

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';
		
	}
		
}

function dynamicChangeTemplate(obj, id, type_id, typeTpl) {
	var val = document.getElementById(id).value;
	var res = util.makePostRequest('/my/s3/types/template.change.php?'+access, 'type_id='+type_id+'&tpl='+val+'&type_tpl='+typeTpl);
	if (!res.error) {
		s3.alert('Шаблон успешно сохранен');
	} else {
		s3.alert('Ошибка при сохранении');
	}
}

function dynamicGenerateTemplate(obj, url) {
	var res = util.makeGetRequest(url);
	if (!res.error) {
		s3.alert('Шаблон успешно сгенерирован');
		window.location.reload();
	} else {
		s3.alert(res.text);
	}
}

