/* =========================================================== */
/* === Модуль универсального браузера графики и инфоблоков === */
/* =========================================================== */
var cUniBrowser=new Function;
cUniBrowser.prototype={
	//Создание окна браузера
	make: function(params) {
		var params=params||{}
		this.width=params['width'] || 500;
		this.height=params['height'] || 500;
		this.min_width=params['min_width'] || 300;
		this.min_height=params['min_height'] || 200;
		this.id=params['id'];
		this.tools_panel_width=0;
		this.opened=false;
		this.no_elements_text=params['no_elements_text']||trans.nothing_in_category;
		this.use_panel=(params['use_panel']===undefined)?true:false;
		this.use_splash=(params['use_splash']===undefined)?true:false;
		
		this.header_h=60;
		this.footer_h=20;
		
		this.min_state=false;
		
		this.data={}
		this.groups={}
		this.cur_group=null;
	
		this.cont=AddElement(document.body,'DIV',{id: this.id+'_cont', className: 'ub_cont', style: {top: '-3000px', left: '-3000px', width: '500px', height: '500px'}});
		this.head=AddElement(this.cont,'DIV',{className: 'ub_head'});
		this.title=AddElement(this.head,'DIV',{id: this.id+'_title', className: 'ub_title', innerHTML: params['title']});
		this.close_but=AddElement(this.head,'A',{className: 'ub_close', href: '#', onclick: OOP_Event(this,'close')});
		this.max_but=AddElement(this.head,'A',{className: 'ub_max', href: '#', onclick: OOP_Event(this,'maxmin')});
		
		this.panel=AddElement(this.head,'DIV',{className: 'ub_panel'});
		this.body=AddElement(this.cont,'DIV',{className: 'ub_body'});
		
		this.status=AddElement(this.cont,'DIV',{className: 'ub_status'});
		this.status_inner=AddElement(this.status,'DIV',{className: 'ub_status_inner'});
		this.corner=AddElement(this.status_inner,'DIV',{id: this.id+'_corner', className: 'ub_status_corner'});
		
		if(this.use_splash) {
			PopUp.ev_add('messages','show',OOP_CallBack(this,function(){
				if(!this.opened) return true;
				this.cont.style.zIndex=5000;
				PopUp.get('messages').style.zIndex=11000;
			}));
			PopUp.ev_add('messages','hide',OOP_CallBack(this,function(){
				if(!this.opened) return true;
				this.cont.style.zIndex=10000;
				Splash.show();
			}));
		}
	 
		DD.add_node(this.title);
		DD.add_node(this.corner);
		
		DD.add_action(this.title.id,{move: OOP_Event(this,'move_cont'), end: OOP_Event(this,'end_cont_drop'), start: OOP_Event(this,'start_cont_drop')});
		DD.add_action(this.corner.id,{move: OOP_Event(this,'cont_resize'), end: OOP_Event(this,'end_cont_resize')});
	},

	/* ==================================== */
	/* ========= Работа с данными ========= */
	/* ==================================== */

	//Добавление групп
	add_groups: function(groups) {
		for(var i in groups) this.groups[i]={name: groups[i].name, parent: groups[i].parent || false, no_elements_text: groups[i].no_elements_text || false, units: {}, fo: true}
	},
	
	//Удаление групп
	delete_groups: function(ids) {
		for(var i=0, id=null; id=ids[i]; i++) delete this.groups[id];
	},
	
	//Добавление или изменение элемента
	add_unit: function(i,cu) {
		if(!this.data[i]) this.data[i]=cu;
		else {
			if(this.data[i]['group']!=cu['group']) delete this.groups[this.data[i]['group']]['units'][i];
			for(k in cu) this.data[i][k]=cu[k];
		}
		if(cu['group']) this.groups[cu['group']]['units'][i]=true;
	},
	
	//Добавление или изменение элементов
	add_units: function(units) {for(var i in units) this.add_unit(i,units[i]);},
	
	//Отрисовка элементов
	draw_units: function() {
		var code=[], units=this.groups[this.cur_group]['units'];
		for(var i in units) code.push("<div class='ub_block'>"+this.draw_one_unit(i)+"</div>");
		if(code.length==0) code=["<div class='ub_no_elements'>",this.groups[this.cur_group]['no_elements_text']||this.no_elements_text,'</div>'];
		this.body.innerHTML=code.join('\n');
	},
	
	//Отрисовка одного элемента
	draw_one_unit: function(id) {return id},
	
	//Удаление элемента/ов
	del_units: function(ids) {
		for(var i=0, id=null; id=ids[i]; i++) {
			delete this.groups[this.data[id]['group']]['units'][id];		
			delete this.data[id];
		}
	},
	
	/* ==================================== */
	/* ======= Навигация по группам ======= */
	/* ==================================== */
	draw_navig_bar: function(type) {
		if(!this.use_panel) return true;
		if(type=='tabs') {
			this.panel.className+=' ub_panel_tabs';
			this.navig_block=AddElement(this.panel,'DIV',{className: 'ub_tabs'});
			this.nav_ul=AddElement(this.navig_block,'UL',{onclick: OOP_Event(this,function(e) {
				var e=e || window.event, target = e.target || e.srcElement;
				while(target.nodeName!='UL') {
					if(target.nodeName=='A') {this.open_group(target.href.replace(/^([^#]*#?)/,'')); break;}
					target=target.parentNode;
				}
				return false;
			})});
			this.draw_tabs();
		}
	},
	
	//Отрисовка табов
	draw_tabs: function() {
		if(!this.use_panel) return true;
		var code=[];
		for(var i in this.groups) code.push("<li"+(i==this.cur_group?" class='ub_tab_current'":"")+"><a href='#"+i+"' onfocus='this.blur()'>"+this.groups[i]['name']+"</a></li>");
		this.nav_ul.innerHTML=code.join('\n');
	},
	
	//Открытие группы
	open_group: function(id) {
		this.body.innerHTML='';
		this.cur_group=id;
		this.draw_tabs();
		
		if(this.groups[this.cur_group]['fo']) this.get_data_list();
		else {this.body.style.backgroundImage="url('/img/sp.gif')"; this.draw_units();}
	},
	
	/* ==================================== */
	/* === Манипуляции с окном браузера === */
	/* ==================================== */
	
	//Добавление левой панели инструментов
	add_panel: function(id,width,name) {
		this.tools_panel=AddElement(this.cont,'DIV',{className: 'ub_tools_panel', id: id, style: {width: width+'px'}, innerHTML: "<div class='ub_tools_panel_name'>"+name+"</div>"});	
		this.tools_panel_width=width;
		this.body.style.left=width+1+'px';
	},	
	
	//Перерисовка габаритов и положения окна
	redraw_geo: function() {
		var params=['left','top','width','height'], min_width=this.min_width, min_height=this.min_height;
		var params_rules={
			'top': function(val) {return val;},
			'left': function(val) {return val;},
			'width': function(val) {return (val>=min_width)?val:min_width;},
			'height': function(val) {return (val>=min_height)?val:min_height;}
		}
		for(var cp=null, i=0, cs=this.cont.style; cp=params[i]; i++) cs[cp]=params_rules[cp](this[cp])+'px';
		this.body.style.width=(params_rules['width'](this.width)-2-this.tools_panel_width)+'px';
		this.body.style.height=(params_rules['height'](this.height)-this.header_h-this.footer_h-3)+'px';
	},	
	
	//Закрытие окна браузера
	close: function() {
		this.cont.style.top=this.cont.style.left='-3000px';
		if(this.use_splash&&Splash) Splash.hide();
		this.opened=false;		
		return false;
	},
	
	//Открытие окна браузера
	open: function() {
		this.opened=true;

	var screen_size=GetScreenSize(), screen_start=GetScreenScroll();
		
		if(this.use_splash&&Splash) Splash.show();
		if(!this.top) {
			this.top=parseInt((screen_size.height+screen_start.y-this.height)/2,10);
			this.left=parseInt((screen_size.width+screen_start.x-this.width)/2,10);
		}
		else {
			if(this.top<screen_start.y) this.top=screen_start.y;
		}
		this.redraw_geo();
		
		this.open_group(this.cur_group);
		return false;
	},
	
	//Максимизация/минимизация окна
	maxmin: function() {
		this.max_but.blur();
		var screen_size=GetScreenSize(), screen_start=GetScreenScroll();
	
		if(!this.min_state) {
			this.min_state={width: this.width, height: this.height, top: this.top, left: this.left}
			this.top=screen_start.y+1;
			this.left=screen_start.x+1;
			this.width=screen_size.width-3;
			this.height=screen_size.height-3;
		}
		else {
			for(var i in this.min_state) {this[i]=this.min_state[i];}
			this.min_state=false;
		}
		
		this.redraw_geo();
		return false;
	},

	//Старт перетаскивания окна браузера
	start_cont_drop: function(coords) {
		this.cont.style.left=this.cont.style.top='-3000px';	
		DD.start_ghost({top: this.top, left: this.left, width: this.width, height: this.height});
	},
	
	//Завершение перетаскивания окна браузера
	end_cont_drop: function(coords) {
		DD.end_ghost();
		this.redraw_geo();
	},
	
	//Перемещение окна браузера
	move_cont: function(coords) {
		this.left+=coords.dx;	
		this.top+=coords.dy;
		DD.change_ghost('move', [this.left,this.top]);
	},
	
	//Изменение размеров окна браузера
	cont_resize: function(coords) {
		this.min_state=false;
		this.width+=coords.dx;	
		this.height+=coords.dy;
		this.redraw_geo();
	},
	
	//Завершение изменения размеров окна браузера
	end_cont_resize: function() {
		if(this.width<this.min_width) this.width=this.min_width;
		if(this.height<this.min_height) this.height=this.min_height;
	}
}

/* ================================= */
/* ======== Модуль Drag&Drop ======= */
/* ================================= */
var cDD=function() {
	var nodes={}
	var evs={move: {}, end: {}, start: {}}
	var f_move=false;
	var ghost=false;
	
	var init=function() {
		addEvent(document,'mousemove',HandlerMove);
		addEvent(document,'mouseup',HandlerUp);
		
		/*
		if(window.frames[0]) {
			addEvent(window.frames[0].document,'mousemove',HandlerMove);
			addEvent(window.frames[0].document,'mouseup',HandlerUp);
		}
		*/
		
		ghost=AddElement(document.body, 'DIV', {style: {position: 'absolute', top: '-1000px', left: '-1000px', zIndex: 11000, backgroundColor: '#A2C4C9', border: '1px solid #45818E', cursor: 'move'}});

		if(!isIE) ghost.style.opacity=0.5;
		else {
			ghost.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=50)";
			//ghost.innerHTML="<iframe class='megaframe'></iframe>";
		}
	}
	
	addEvent(window,'load',init);
	
	//Добавление элемента, доступного для перетаскивания
	this.add_node=function(id,params) {
		var params=params || {}
		params.self_drag=params.self_drag||false;
		params.strict_target=params.strict_target||false;
		params.trigger=params.trigger||false;
		
		var elem = typeof(id)=="string" ? $n(id) : id;
		nodes[elem.id]=params;
		
		addEvent(elem,'mousedown',HandlerDown);
		if(isIE) elem.ondragstart=function(){return false;}
	}
	
	//Удаление элемента, доступного для перетаскивания
	this.remove_node=function(id) {
		var elem = typeof(id)=="string" ? $n(id) : id;
		delete nodes[elem.id];
		//removeEvent(elem,'mousedown',HandlerDown);
		for(var i in evs) {
			delete evs[i][id];
		}
	}
	
	//Добавление функции обратного вызова при совершении события
	this.add_action=function(id,acts) {
		for(var i in acts) {evs[i][id]=acts[i];}
	}
	
	//Показ "призрака" в начале перетаскивания
	this.start_ghost=function(coords) {
		for(var i in coords) {ghost.style[i]=coords[i]+'px';}
	}
	
	//Перетаскивание или изменение размеров "призрака"
	this.change_ghost=function(type,vals) {
		ghost.style[(type=='move')?'left':'width']=vals[0]+'px';
		ghost.style[(type=='move')?'top':'height']=vals[1]+'px';
	}
	
	//Прячем "призрака" после перетаскивания
	this.end_ghost=function() {
		ghost.style.top=ghost.style.left='-3000px';
	}
	
	//Обработчик отпускания мыши
	var HandlerUp=function(e) {
		if(!f_move) return true;

		/*
		document.body.onselectstart = null;		
		if(window.frames[0] && window.frames[0].document.body) window.frames[0].document.body.onselectstart = null;
		*/
		
		var delta_x=f_move.start_x-f_move.prev_x, delta_y=f_move.start_y-f_move.prev_y;
		for(var i in evs.end) {
			if(i==f_move.cur_id) {evs.end[i]({x: f_move.prev_x, y: f_move.prev_y, dx: delta_x, dy: delta_y},i);}
		}			
		f_move=false;
	}
	
	//Обработчик нажатия мыши
	var HandlerDown=function(e) {
		if(f_move) return true;
		var e=e || window.event || window.frames[0].event, target = e.target || e.srcElement, tid=target.id||false;
		
		/*
		document.body.onselectstart = function(){return false;}
		if(window.frames[0] && window.frames[0].document.body) window.frames[0].document.body.onselectstart = function(){return false;}
		*/

		if(!nodes[tid]) {
			while(target=target.parentNode) { if(target.id && nodes[target.id]) {tid=target.id; break;}}
			if(tid && nodes[tid].strict_target===true) tid=false;
		}
		if(!nodes[tid]) return true;
		
		//Проверка условия перетаскивания
		if(nodes[tid].trigger && window[nodes[tid].trigger]===false) return true;
		
		ControlEvent(e,'bd');
		
		var coords=GetMouse(e);
		f_move={
			cur_id: tid,
			cur_elem: nodes[tid],
			start_x: coords.x,
			start_y: coords.y,
			prev_x: coords.x,
			prev_y: coords.y
		}
		
		//if(f_move.cur_elem.self_drag) f_move.elem_coords=getElementPosition(tid);
		
		for(var i in evs.start) {
			if(i==f_move.cur_id) {evs.start[i]({x: coords.x, y: coords.y},i);}
		}		
	}

	//Обработчик перетаскивания мыши
	var HandlerMove=function(e) {
		if(!f_move) return true;
		
		var coords=GetMouse(e);
		
		if(coords.y < 10) coords.y = 10;

		var delta_x=coords.x-f_move.prev_x, delta_y=coords.y-f_move.prev_y;
		var delta_start_x=coords.x-f_move.start_x, delta_start_y=coords.y-f_move.start_y;

		f_move.prev_x = coords.x;
		f_move.prev_y = coords.y;
		
		if(f_move.cur_elem.self_drag) {
			var el_style=$n(f_move.cur_id).style;
			el_style.top=parseInt(el_style.top)+delta_y+'px';
			el_style.left=parseInt(el_style.left)+delta_x+'px';
		}

		for(var i in evs.move) {
			if(i==f_move.cur_id) {evs.move[i]({x: coords.x, y: coords.y, dx: delta_x, dy: delta_y, dsx: delta_start_x, dsy: delta_start_y},i);}
		}
	}	
	
	//Принудительный сброс перетаскивания
	this.end_drag=function() {HandlerUp(); return false;}
}
var DD=new cDD();

var cur_win=null;
function myCustomFileBrowser(field_name, url, type, win) {
	switch(type) {
		case 'image':
		var cur_input=win.document.forms[0].elements[field_name];
		cur_win=win;
		ImageBrowser.SetParams(false,[cur_input,'TinyCallback']);
		break;
		
		case 'file': break;
	}
	return false;
}
