
function message_box_close() {
	$('#loading-layer').hide();
}


function message_box(text,img,actions,nosc) 
{
//actions - array of Object{text,img,func}	
	if (text) $('#loading-text').html(text);
	if (img) {
		$('#loading-img').html('<img src="'+img+'">');
		$('#loading-img').show();
	}
	if (actions!=undefined) {
		var html = '';
		for (var i=0;i<actions.length;i++)
			switch (actions[i].func) {
				case 'std_cancel':
					html += '<a onclick="message_box_close()"><img class="image" src="/_admincp/_design/img/forms/btn_close.png">&nbsp;<b>'+language.mb_actCancel+'</b></a>';
				break;
				default:
					html += '<a onClick="'+actions[i].func+'">';
					if (actions[i].img) html += '<img src="'+actions[i].img+'">';
					html += '&nbsp;<strong>'+actions[i].text+'</strong>';
			}
		$('#loading-actions').html(html);
		$('#loading-actions').show();
	}
	$('#loading-layer').show();
	var new_height = $('#loading-layer').attr('offsetHeight');
	var new_width = $('#loading-layer').attr('offsetWidth');
	var top = ((document.body.scrollTop>0 ? document.body.scrollTop : document.documentElement.scrollTop)+(document.body.clientHeight/2)-(new_height/2)-30)+'px';
	var left = ((document.body.clientWidth/2)-(new_width/2))+'px';
	$('#loading-layer').css('top',top);
	$('#loading-layer').css('left',left);
	if (!nosc) shortcut.add("Esc", function(){message_box_close();shortcut.remove("Esc");});
	//!!! what should we do if we already have ESC event???
}

function CatModuleAct(id,act,clas,act_param_value,table) {
	if (!clas) clas = 'Category';
	if (!table) table = 'module';
	if (!act_param_value) act_param_value = '';
	eval('var cap = language.mb_processing_'+act);
	message_box(cap,'/_admincp/_design/img/bar/loading.gif','');
	$.ajax({
		type: "POST",
		url: "/_admincp/_core/_ajax/action.php",
		data: "class="+clas+"&act="+act+"&id="+id+"&act_param_value="+act_param_value+"&table="+table,
		success: function(msg){
			message_box_close();
			eval(msg);
		}
	});
}

function reactProcess(obj,conf) {
	var g = conf!=undefined ? confirm(language.are_you_sure) : true;

	if (g) {
		var a = obj.id.match(/^react_([^_]+)_([^_]+)_([0-9]+)_?([^_]*)_?(.*)$/);
		$.ajax({
			type: "POST",
			url: "/_admincp/_core/_ajax/reaction.php",
			data: "class="+a[1]+"&act="+a[2]+"&id="+a[3]+"&act_param_value="+a[4]+"&table="+a[5],
			success: function(msg){
				eval(msg);
			}
		});
	}
}

dtree_loaded = new Array();
function dtree_LoadCategory(id,_io,tree_var,set_urls) {
	if (!_io) {
		for (var n=0;n<dtree_loaded.length;n++)
			if (dtree_loaded[n]==id) return;
		
		document.body.style.cursor = 'wait';
		$.ajax({
			type: "POST",
			url: "/_admincp/_core/Libraries/Category/ajax/open_submenu.php",
			data: "id="+id+"&tree_var="+tree_var+"&set_urls="+set_urls,
			success: function(msg){
				eval(msg);
				dtree_loaded.push(id);
				document.body.style.cursor = 'default';
			}
		});
	}
}

Init_Post = new Array();
function Init() {

	//toggle Enter key in textareas
	$('textarea').focus(function(){shortcut.remove("Enter")});
	$('textarea').blur(function(){shortcut.remove("Enter");shortcut.add("Enter", function(){$("#save_class, #save_module").trigger("click")})});

	//highlighting
	$('.enable_highlight').hover(
		function () {
			$(this).addClass('highlight');
		}, 
		function () {
			$(this).removeClass('highlight');
		}
    );
	
	//movings
	$('img.catmod_move_before').unbind('mouseover','click');
	$('img.catmod_move_before').mouseover(function(){
		showhint(language.catmod_move_before+' <strong>'+$(this).parents(':first').text()+'</strong>', this, null, '278px');
	});
	
	$('img.catmod_move_into').unbind('mouseover','click');
	$('img.catmod_move_into').mouseover(function(){
		showhint(language.catmod_move_into+' <strong>'+$(this).parents(':first').text()+'</strong>', this, null, '278px');
	});
	
	$('img.catmod_move_before,img.catmod_move_into').click(function(){
		var t = this.id;
		$.ajax({
			type: "POST",
			url: "/_admincp/_core/_ajax/move_catmod.php",
			data: "table="+$('input[name=catmodule]').val()+"&id_cat="+t+"&id="+$('#ID_Module').val()+"&act="+$(this).attr('class').replace('catmod_move_',''),
			success: function(msg){
				window.parent.parent.location = '/_admincp/index.php?category='+msg;
			}
		});
	});

	//removing tr
	$('img.delete_element').unbind('click');
	$('img.delete_element').click(function() {
		var prefix = $('#module_prefix').val();
		
		function DeleteLine() {
			if (curr.find('img[src*=Up_]').attr('src')) {
				
				var pos = parseInt(curr.attr('pos')), next_pos = Infinity, prev_pos = 0, new_src;
				
				curr.siblings('[pos][locked!=1]').each(function(i){
					if (parseInt($(this).attr('pos')) > pos && parseInt($(this).attr('pos')) < next_pos) {
						next_pos = $(this).attr('pos');
					}
					if (parseInt($(this).attr('pos')) < pos && parseInt($(this).attr('pos')) > prev_pos) {
						prev_pos = $(this).attr('pos');
					}
				});

				if (next_pos == Infinity && prev_pos != 0) {
					if (new_src = curr.siblings('[pos='+prev_pos+']').find('img[src$=Down_1.gif]').attr('src'))
						curr.siblings('[pos='+prev_pos+']').find('img[src$=Down_1.gif]').attr('src',new_src.replace('Down_1.gif','Down_0.gif'));
				}
				
				if (prev_pos == 0 && next_pos != Infinity) {
					if (new_src = curr.siblings('[pos='+next_pos+']').find('img[src$=Up_1.gif]').attr('src'))
						curr.siblings('[pos='+next_pos+']').find('img[src$=Up_1.gif]').attr('src',new_src.replace('Up_1.gif','Up_0.gif'));
				}
				
				//update next lines
				curr.siblings('tr[id^='+prefix+']').each(function(i){
					if (parseInt($(this).attr('pos')) > parseInt(curr.attr('pos'))) {
						$(this).attr('pos',parseInt($(this).attr('pos'))-1);
						$(this).find('td.pos').html($(this).attr('pos'));
					}
				});
			}
			curr.remove();
		}
		
		var t = $(this);
		var curr = t.parents('tr:first');
		var a = curr.attr('id').match(/(.*?)_([0-9]+)$/);
		if (!curr.parents('table:first,tbody:first').hasClass('noajax') && confirm(language.are_you_sure)) {
			message_box(language.mb_processing_delete,'/_admincp/_design/img/bar/loading.gif');
			$.ajax({
				type: "POST",
				url: "/_admincp/_core/Modules/_ajax/delete_line.php",
				data: "table="+a[1]+"&id="+a[2],
				success: function(msg){
					DeleteLine();
					message_box_close();
				}
			});
		} else DeleteLine();
		
		try { fdTableSort.initEvt(); } catch(err) {};
    });

	//onoff switches
	$('img.onoff').unbind('click');
	$('img.onoff').click(function() {
		function OnoffLine() {
			t.src = t.src.replace(/\/_(\w+)_(0|1)\.(\w+)$/,'/_$1_'+act+'.$3');
			$(t).siblings('input[name="'+t.id+'"]').val(act);
		}
		
		var t = this;
		var act = t.src.match(/\/_\w+_(0|1)\.\w+$/)[1]==1 ? 0 : 1;
		
		var this_node = $(t).parents('.NodeParent:first');
		var parent_node = this_node.parents(':first');
		
		if (t.id.match(/\[Default\]$/)) {
			$(parent_node).find('img[id*=[Default]]').attr('src',t.src.replace(/\/_(\w+)_(0|1)\.(\w+)$/,'/_$1_0.$3'));
			$(parent_node).find('input[name*=[Default]]').val(0);
		}
		
		if (!parent_node.hasClass('noajax')) {
			var a = this_node.attr('id').match(/(.*?)_([0-9]+)$/);
			var prefix = a[1];
			message_box(language.mb_processing,'/_admincp/_design/img/bar/loading.gif');
			$.ajax({
				type: "POST",
				url: "/_admincp/_core/_ajax/onoff_line.php",
				data: "table="+prefix+"&column="+t.id+"&act="+act+"&id="+a[2],
				success: function(msg){
					OnoffLine();
					message_box_close();
				}
			});
		} else OnoffLine();
    });
	
	//position
	$('img.move').unbind('click');
	$('img.move').click(function() {
		
		if (!this.src.match(/(Up|Down)_1\.\w+$/)) return;
		
		function MoveLine() {
			do {
				newpos += dir;
				switch_node = parent_node.children('[pos='+(newpos)+']');
			} while (switch_node.attr('id') && switch_node.attr('locked')==1);
			
			if (switch_node.attr('id')) {
				dir==1 ? this_node.insertAfter(switch_node) : this_node.insertBefore(switch_node);
				
				if (Math.abs(newpos-pos)>1)
					dir==1 ? switch_node.insertBefore(parent_node.children('[pos='+(pos+1)+']')) : switch_node.insertAfter(parent_node.children('[pos='+(pos-1)+']'));
				
				//td.pos поставлено для мгновенного обновления столбца, который выдаёт номер позиции
				switch_node.attr('pos',pos);
				switch_node.find('td.pos').html(pos);
				
				this_node.attr('pos',newpos);
				this_node.find('td.pos').html(newpos);
			}
			
			//обновление картинки в зависимости от наличия следующей/предыдущей строки
			var a_down = a_up = s_a_up = s_a_down = 0;
			this_node.siblings('[pos][locked!=1]').each(function(){	if ($(this).attr('pos') > newpos) {		a_down = 1; return;	} });
			switch_node.siblings('[pos][locked!=1]').each(function(){	if ($(this).attr('pos') < pos) {	s_a_up = 1; return;	} });
			this_node.siblings('[pos][locked!=1]').each(function(){	if ($(this).attr('pos') < newpos) {		a_up = 1; return;	} });
			switch_node.siblings('[pos][locked!=1]').each(function(){	if ($(this).attr('pos') > pos) {	s_a_down = 1; return;	} });

			try {
				this_node.find('img[src*=Up_]').attr('src',this_node.find('img[src*=Up_]').attr('src').replace(/Up_\d(\.\w+)/,'Up_'+a_up+'$1'));
				this_node.find('img[src*=Up_]').css('cursor',a_up ? 'pointer' : 'default');
				
				this_node.find('img[src*=Down_]').attr('src',this_node.find('img[src*=Down_]').attr('src').replace(/Down_\d(\.\w+)/,'Down_'+a_down+'$1'));
				this_node.find('img[src*=Down_]').css('cursor',a_down ? 'pointer' : 'default');
				
				switch_node.find('img[src*=Up_]').attr('src',switch_node.find('img[src*=Up_]').attr('src').replace(/Up_\d(\.\w+)/,'Up_'+s_a_up+'$1'));
				switch_node.find('img[src*=Up_]').css('cursor',s_a_up ? 'pointer' : 'default');
				
				switch_node.find('img[src*=Down_]').attr('src',switch_node.find('img[src*=Down_]').attr('src').replace(/Down_\d(\.\w+)/,'Down_'+s_a_down+'$1'));
	
				switch_node.find('img[src*=Down_]').css('cursor',s_a_down ? 'pointer' : 'default');
			} catch(err) {}
		}
		
		var a = this.src.match(/(Up|Down)_1\.\w+$/);
		var dir = a[1]=='Up' ? -1 : 1;
		
		var switch_node;
		var this_node = $(this).parents('[pos]:first');
		
		a = this_node.attr('id').match(/(.*?)_([0-9]+)$/);
		var prefix = a[1];
		
		var parent_node = this_node.parents('[id^='+prefix+']:first');
		
		var pos = parseInt(this_node.attr('pos'));
		var newpos = pos;
		
		MoveLine();
		
		if (switch_node.attr('id')) {
			var switch_id = switch_node.attr('id').match(/_([0-9]+)$/)[1];
			if (!parent_node.hasClass('noajax')) {
				message_box(language.mb_processing,'/_admincp/_design/img/bar/loading.gif');
				$.ajax({
					type: "POST",
					url: "/_admincp/_core/_ajax/move_line.php",
					data: "table="+prefix+"&dir="+dir+"&id="+a[2]+"&switch_id="+switch_id+"&pos="+pos+"&newpos="+newpos,
					success: function(msg){
						message_box_close();
					}
				});
			}
		}
		
		try { fdTableSort.initEvt(); } catch(err) {};
	});
	
	//add element
	$('.add').unbind('click');
	$('.add').click(function() {

		var id_node_add_to = $(this).attr('rel');

		var new_tag = $('[rel='+id_node_add_to+'_new]').clone();
		
		$('#'+id_node_add_to).append(new_tag);
		
		var id_new_tag = new_tag.attr('id');
		var tag_prefix = id_node_add_to.replace(/\d+$/,'');
		
		var maxpos = 0;
		new_tag.siblings('[pos]').each(function(){	if (parseInt($(this).attr('pos')) > maxpos) maxpos = parseInt($(this).attr('pos')); });
		
		var prev = new_tag.siblings('[pos='+maxpos+']');
		
		if (prev.attr('id')) {
			var a = prev.attr('id').match(/([0-9]+)$/);
			n = parseInt(a[1],10) + 1;
		} else n = 1;
		
		new_tag.attr('id',id_new_tag+n);
		new_tag.find('[name*=[_]]').each(function() {	$(this).attr('name',$(this).attr('name').replace(/\[_\]/,'[_'+n+']'));	});
		new_tag.find('[id*=[_]]').each(function() {	$(this).attr('id',$(this).attr('id').replace(/\[_\]/,'[_'+n+']'));	});
		new_tag.find('img[src*=Up_],img[src*=Down_]').addClass('move');
		if (prev.attr('pos')) {
			new_tag.attr('pos',++maxpos);
			new_tag.find('td.pos').html(maxpos);
			
			if (new_tag.find('img[src*=Up_]').length) { 
				maxpos = 0;
				new_tag.siblings('[pos][locked!=1]').each(function(i){
					if (parseInt($(this).attr('pos')) > maxpos) maxpos = parseInt($(this).attr('pos'));
				});
				
				var prev_mov = new_tag.siblings('[pos='+maxpos+']');
				
				if (prev_mov.attr('id')) {
					prev_mov.find('img[src*=Down_]').attr('src',prev_mov.find('img[src*=Down_]').attr('src').replace(/Down_\d(\.\w+)/,'Down_1$1'));
					prev_mov.find('img[src*=Down_]').css('cursor','pointer');
					//prev_mov.find('img[src*=Down_]').addClass('move');
					new_tag.find('img[src*=Up_]').attr('src',new_tag.find('img[src*=Up_]').attr('src').replace(/Up_\d(\.\w+)/,'Up_1$1'));
					new_tag.find('img[src*=Up_]').css('cursor','pointer');
					//new_tag.find('img[src*=Up_]').addClass('move');
				}
			}
		} else {
			new_tag.attr('pos',1);
			new_tag.find('td.pos').html(1);
		}

		new_tag.removeAttr('rel');
		new_tag.removeAttr('locked');
		Init();
		try { fdTableSort.initEvt(); } catch(err) {};
	});

	$('select.typebox').change(function(){
		var a;
		if (a = $(this).val().match(/^list_(\w+)/)) {
			var lists = $(this).siblings('div.lists');
			
			if (lists.length==0 || 
				(a[1]!='user' && lists.find('select').hasClass('usergroup')) ||
				(a[1]=='user' && !lists.find('select').hasClass('usergroup'))
			) {
				if (lists.length!=0) $(this).siblings('div.lists').remove();
				var id = $(this).attr('name').replace(/[\w\d]+\[([_\d]+)\]\[Type\]/,'$1');
				$(this).after($('div.'+(a[1]=='user' ? 'usergroup_source' : 'listy_source')).html());
				var new_select = $(this).siblings('div.lists').find('select');
				new_select.attr('name',new_select.attr('name').replace(/\[_\]\[ID_List\]/,'['+id+'][ID_List]'));
			}
		} else {
			$(this).siblings('div.lists').remove();
		}
	});
		
	for (i=0;i<Init_Post.length;i++) Init_Post[i]();
}

function FixPositioning(selector) {
	var cancel = true;
	var pos;
	$(selector).find('img[src*=_Down_1.]').each(function(){
		pos = $(this).parents('.NodeParent:first').attr('pos');

		$(this).parents('.NodeParent:first').siblings('[pos][locked!=1]').each(function(){
			if ($(this).attr('pos') > pos) {
				cancel = false;
				return;
			}
		});
		
		if (cancel) {
			$(this).unbind('click');
			$(this).attr('src',$(this).attr('src').replace('_Down_1.','_Down_0.'));
		} else cancel = true;
	});

	$(selector).find('img[src*=_Up_1.]').each(function(){
		pos = $(this).parents('.NodeParent:first').attr('pos');
		$(this).parents('.NodeParent:first').siblings('[pos][locked!=1]').each(function(){
			if ($(this).attr('pos') < pos) {
				cancel = false;
				return;
			}
		});
		
		if (cancel) {
			$(this).unbind('click');
			$(this).attr('src',$(this).attr('src').replace('_Up_1.','_Up_0.'));
		}
	});
}

$(document).ready(function(){
	Init();
	
	//toggle leftcol blocks
	$('h1[id^=masterNavh]').click(function(){
		i = this.id.replace('masterNavh','');
		$('div[id$=masterNavLinks'+i+']').toggle();
		if ($(this).hasClass('active')) { $(this).removeClass('active'); $(this).addClass('inactive'); }
		else { $(this).removeClass('inactive'); $(this).addClass('active'); }
	});
	
	//обработка действий с категорией и модулем
	//if onClick already present - do nothing
	$('[id^=react_]').click(function(){
		if (!$(this).attr('onClick')) reactProcess(this);
	});
	
	//события стандартных кнопок в Greybox
	if ($('a#close').attr('href')=='#')
		$('a#close').click(function(){close_box()});
	
	$('a#refresh').click(function(){location.reload();});

	$('a[id=clear]').click(function() {
		$(':input').val('');
		
		var j = 0;
		$('textarea[id^=Text]').each(function(){
			if (document.getElementById('mce_editor_'+j) != null) tinyMCE.execInstanceCommand('mce_editor_'+j,'mceSetContent',false,' ');
			j++;
		});
	});
	//-----------------------------------

});

function fileBrowserCallBack(field_name, url, type, win) {
	var connector = "/js/file_manager/file_manager.php";
	my_field = field_name;
	my_win = win;
	switch(type)
	{
		case "image":
		{
			connector += "?type=img";
			break;
		}
		case "flash":
		{
			connector += "?type=flash";
			break;
		}
		case "qt":
		{
			connector += "?type=qt";
			break;
		}
		case "shockwave":
		{
			connector += "?type=shockwave";
			break;
		}
		case "wmp":
		{
			connector += "?type=wmp";
			break;
		}
		case "rmp":
		{
			connector += "?type=rmp";
			break;
		}
		default:
		{
			connector+="?type=files";
			break;
		}
	}
	window.open(connector, "file manager", "modal,width=450,height=600");
}

function TinyMCE_std() {
	tinyMCE.init({
		// General options
		language : "ru",
		mode : "exact",
	  	elements : "Text1, Text2, Text3, Text4, Text5, FullText,image_desc",		
		theme : "advanced",
		force_br_newlines : true,
		force_p_newlines : false,
		convert_url: false,
		plugins : "pagebreak,style,table,advhr,advimage,advlink,inlinepopups,insertdatetime,preview,media,searchreplace,contextmenu,paste,fullscreen,noneditable,nonbreaking",
		file_browser_callback : "fileBrowserCallBack",
		// Theme options
		theme_advanced_buttons1 : "newdocument,|,undo,redo,|,bold,italic,underline,strikethrough,|,bullist,numlist,|,outdent,indent,|,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,backcolor,|,preview,fullscreen", 
		theme_advanced_buttons2 : "tablecontrols,|,hr,removeformat,|,anchor,link,unlink,image,media,|,code",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true
	});
/*
	tinyMCE.init({
		// General options
//		language: "ru_CP1251",

		// Theme options

		extended_valid_elements : "noindex,div[align|style|class|id],script[src|type],a[class|style|rel|name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|style|href|rel|onclick|onmouseover|onmouseout|name|usemap],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],iframe[class|marginWidth|marginHeight|src|frameBorder|width|scrolling|height],area[title|shape|alt|coords|href],map[name]",
		file_browser_callback : "mcFileManager.filebrowserCallBack",
		tab_focus : ":prev,:next"
	});
	*/
}

function TinyMCE_short() {
	tinyMCE.init({
		// General options
		language : "ru",
		mode : "exact",
	  	elements : "Text1, Text2, Text3, Text4, Text5",
		theme : "advanced",
		force_br_newlines : true,
		force_p_newlines : false,

		plugins : "style,advhr,advimage,advlink,inlinepopups",

		// Theme options
		theme_advanced_buttons1 : "newdocument,|,undo,redo,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,backcolor,|,link,unlink,|,code", 
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true
	});
}


var index_id=0;

function _Calendat_mouseover()
{
	$(this).unbind('mouseover');
	this.id="_"+index_id;
	index_id+=1;
	Calendar_setup(this.id,$(this).attr('dateformat'));
	$('input.calendar').live('mouseover',_Calendat_mouseover);
}

function Calendar_setup_all()
{
	$('input.calendar').live('mouseover',_Calendat_mouseover);
}

function Calendar_setup(suffix,format) 
{
	/*
		if (format==undefined) format = "%Y-%m-%d %H:%M";
		Calendar.setup({
			inputField     :    suffix,          // id of the input field
			ifFormat       :    format,    // format of the input field
			button         :    suffix, 	 // trigger for the calendar (button ID)
			align          :    "Br",          	 // alignment
			timeFormat     :    "24",
			showsTime      :    true,
			singleClick    :    true,
		});
	*/
	if (format==undefined) format = "%Y-%m-%d %H:%M";
    Calendar.setup({ inputField:suffix, ifFormat:format,button:suffix,align:"Br",timeFormat:"24",showsTime:true,singleClick:true});
	
}


// === migom.com PROJECT ===

// перерисовка страницы
function reloadPage() {
	document.body.style.display="inline";
	document.body.style.display="block";
}

// выбор страниц для отображения
function selectPage(current) {
	if (current.parentNode.className!="active") {
		var pos = current.href.lastIndexOf("#");
		where = current.href.slice(pos+1);
		where = document.getElementById(where);

		var nav = current.parentNode.parentNode.getElementsByTagName('li');
		for(var i=0; i<nav.length; i++) nav[i].className="";
		current.parentNode.className="active";

		nav = document.getElementById("switch").getElementsByTagName('div');
		for(var i=0; i<nav.length; i++) {
			var navClass=nav[i].className;
			if (navClass.indexOf("switch-content")!=-1) if(navClass.indexOf("on")!=-1) nav[i].className=navClass.replace(" on", "");
			if (nav[i].id==where.id) where.className+=" on";
		}
		reloadPage();
	}
	return false;
}


// показать попап
function showPopup(current) {
	showShadow();
	if (current == 'auth') $(current).style.top = '30%';
	$(current).style.display = "block";
	reloadPage();
	return false;
}
// спратать попап
function hidePopup(current) {
	hideShadow();
	$(current).style.display = "none";
	close_message();
	reloadPage();
	return false;
}

function removeMapPopup(current) {
	hideShadow();
	jQuery('#'+current).remove();
	close_message();
	reloadPage();
	return false;
}

// показать тень
function showShadow() {
	var shadow = document.getElementById("shadow");
	shadow.style.display = "block";

	/*if(ie) {
		document.body.className += " hideselects";
		document.getElementById('punkt').className = "punkt";
	}*/

	var bodyHeight = document.body.clientHeight;
	var wrapHeight = document.getElementById("wrap").clientHeight;

	if (wrapHeight > bodyHeight) shadowHeight = wrapHeight;
	else shadowHeight = bodyHeight;
	shadow.style.height = shadowHeight + "px";
	return false;
}

// спрятать тень
function hideShadow() {
	var shadow = document.getElementById("shadow");
	shadow.style.display = "none";
	/*if(ie) {
		document.body.className = document.body.className.replace(" hideselects", "");
		document.getElementById('punkt').className = "";
	}*/
	return false;
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}
function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();
    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


// === END OF migom.com PROJECT ===

// UNREVIED BELOW
var vertical_offset="0" //horizontal offset of hint box from anchor link. No need to change.
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
}
else{
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
}
return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth){
if ((ie||ns6) && document.getElementById("hintbox")){
dropmenuobj=document.getElementById("hintbox")
dropmenuobj.innerHTML=menucontents
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (tipwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=tipwidth
}
//alert(dropmenuobj.style.zindex);
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
dropmenuobj.style.visibility="visible"
obj.onmouseout=hidetip
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
}

function createhintbox(){
var divblock=document.createElement("div")
divblock.setAttribute("id", "hintbox")
document.body.appendChild(divblock)
}

if (window.addEventListener)
window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
window.attachEvent("onload", createhintbox)
else if (document.getElementById)
window.onload=createhintbox

close_box = function() {
parent.parent.GB_hide();
}

var OK = false;
var remove_func;
var set_focus;

//function $$(e){ return document.getElementById(e); }
function change_class(e){ if (e!=null && e.value!='') e.className = 'inp_text'; }

function _key(event)	{

if(event) {
	 var k = event.keyCode;
	 if(k==0) k=event.charCode;
	 if(k==13 && $$('loading-layer').style.display == 'block')  {
		    $$('loading-layer').style.display = 'none';
		    if (OK==true) remove_func();
		    if ($$(set_focus)!=null) {
		    	if (set_focus != '' && set_focus != undefined) set_focus.focus();
				if ($$(set_focus).className == 'inp_text') $$(set_focus).className = 'inp_text_err';
		    	}
		    return false;
		    }
	 if(k==27) {

		    if ($$('loading-layer').style.display == 'block') $$('loading-layer').style.display = 'none';
		    else if (parent.parent.GB_CURRENT != null) parent.parent.GB_hide();
		    if (set_focus!=null) {
		    	if (set_focus != '' && set_focus != undefined) set_focus.focus();
				if ($$(set_focus).className == 'inp_text') $$(set_focus).className = 'inp_text_err';
		    	}
		   }
}

}

function show_message(text){
	if (text==undefined) text = 'Обработка данных';
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	$$('loading-layer').style.width = '200px';
//	$$('loading-layer').style.height = '60px';
	$$('loading-layer').style.height = 'auto';
	$$('loading-layer').style.textAlign = 'center';
	$$('loading-layer').style.display = 'block';
   	$$('loading-actions').style.display = 'none';
	if (self.screen) $$('loading-layer').style.top = (parseInt(top,10)+(screen.height/2)-200)+'px';
	else $$('loading-layer').style.top = (parseInt(top,10)+(document.body.clientHeight/2)-90)+'px';
	$$('loading-layer').style.left = ((document.body.clientWidth/2)-100)+'px';
	$$('loading-img').style.display = '';
	$$('loading-text').innerHTML = text+', пожалуйста подождите...';
}

function close_message(status, text, focus, action){
	if (status==undefined && $$('loading-layer') && $$('loading-layer').style.display == 'none') return false;
    OK = false;
	$$('loading-layer').style.display = 'block';
	$$('loading-layer').style.textAlign = 'left';
	if (navigator.appName == 'Opera') {
		$$('loading-layer').style.width = '200px';
		$$('loading-layer').style.height = '60px';
	}
	else {
		$$('loading-layer').style.width = 'auto';
		$$('loading-layer').style.height = 'auto';
	}

	$$('loading-actions').innerHTML = '<br />';
   	$$('loading-actions').style.display = 'none';

	if (text==undefined && status!='error') text = 'Информация';
	if (action==undefined) action = '';

	if (status==undefined) {
		$$('loading-layer').style.display = 'none';
		return false;
		}
	else if (status=='info') {
		$$('loading-img').style.display = 'none';
		$$('loading-text').innerHTML = '<br /><img class="image" src="/_admincp/_design/img/icons/warning.png" style="float: left;" hspace="7" vspace="7" /><div style="float: left; text-align: left;">'+text+'</div><div style="clear: both;"></div>';
		$$('loading-actions').innerHTML += '&nbsp;&nbsp;<a href="#" title="Закрыть (ESC)" onclick="$$(\'loading-layer\').style.display = \'none\'; if (set_focus != \'\') set_focus.focus(); return false;"><img class="image" src="/_admincp/_design/img/forms/btn_close.png">&nbsp;<b>Закрыть</b></a>';
	    	$$('loading-actions').style.display = '';

	} else if (status=='confirm') {
		OK = true;
		if (action) remove_func = new Function(action);
		$$('loading-img').style.display = 'none';
		$$('loading-text').innerHTML = '<br /><img class="image" src="/_admincp/_design/img/icons/warning.png" />&nbsp;'+text+'';
		$$('loading-actions').innerHTML += '&nbsp;&nbsp;<a href="#" title="Подтвердить действие (Enter)" onclick="$$(\'loading-layer\').style.display = \'none\'; if (OK==true) remove_func(); return false;"><img class="image" src="/_admincp/_design/img/forms/btn_apply.png">&nbsp;<b>OK</b></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" title="Отменить действие (ESC)" onclick="$$(\'loading-layer\').style.display = \'none\'; return false;"><img class="image" src="/_admincp/_design/img/forms/btn_close.png">&nbsp;<b>Отмена</b></a>';
	    	$$('loading-actions').style.display = '';

	} else if (status=='step') {
		OK = true;
		$$('loading-img').style.display = 'none';
		$$('loading-text').innerHTML = '<br />&nbsp;'+text;
		$$('loading-actions').innerHTML += '<a href="#" onclick="'+action+';"><b>Далее</b>&nbsp;<img class="image" src="/_admincp/_design/img/forms/btn_show_sidebar.png"></a>';
	    	$$('loading-actions').style.display = '';

	} else if (status=='error') {
		$$('loading-img').style.display = 'none';
		if (text==undefined) text = 'Произошла ошибка';
		$$('loading-text').innerHTML = '<br /><img class="image" src="/_admincp/_design/img/icons/error.png" />&nbsp;'+text+'';
	        $$('loading-actions').style.display = '';
		$$('loading-actions').innerHTML += '&nbsp;&nbsp;<a href="#" title="Закрыть (ESC)" onclick="$$(\'loading-layer\').style.display = \'none\'; if (set_focus != \'\') set_focus.focus(); return false;"><img class="image" src="/_admincp/_design/img/forms/btn_close.png">&nbsp;<b>Закрыть</b></a>';
	}

	if ($$('loading-layer').offsetHeight>500){
		$$('loading-layer').style.height = '500px';
		$$('loading-layer').style.overflow = 'auto';
		}

	var new_height = $$('loading-layer').offsetHeight;
	var top = (document.body.scrollTop>0) ? document.body.scrollTop : document.documentElement.scrollTop;
	$$('loading-layer').style.top = (parseInt(top,10)+(document.body.clientHeight/2)-(new_height/2)-30)+'px';
	var new_width = $$('loading-layer').offsetWidth;
   	$$('loading-layer').style.left = ((document.body.clientWidth/2)-(new_width/2))+'px';
	if (focus!=undefined && $$(focus)!=null) {
		    set_focus = $$(focus);
        	if (set_focus!=null && set_focus.className == 'inp_text') set_focus.className = 'inp_text_err';
		}
	else set_focus = '';

	$$('loading-layer').focus();

}

// ОЧИСТКА КЕША
function ask_clear_cache(files){
  var text = (files == undefined || files =='') ? 'сайта': 'модуля';
  close_message('confirm', 'Вы действительно хотите кеш '+text+'?');
  remove_func = new Function("clear_cache('"+files+"');");
}

function clear_cache(files){
  var req = new JsHttpRequest();
  	req.open(null, '/_admincp/_sections/_modules/category/files/_ajax/category/clear_cache.php', true);
 	var text = (files=='undefined' || files =='') ? 'сайта': 'модуля';
  	if (files=='undefined' || files =='') files = '';

	var data = { 'files': files };

 	req.send(data);
	show_message('Очистка кеш-файлов '+text);

    req.onreadystatechange = function() {
     //$$('debug').innerHTML = req.responseText;
		if (req.readyState == 4) {

		//if (req.responseJS.error) {	close_message('error', 'Возникла ошибка при удалении кеш '+text); return false; }
		close_message('info', 'Кеш '+text+' успешно очищен!<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" style="text-decoration: underline;" onclick="location.reload();">обновить страницу</a>');
		}
    }
}





function new_window(id, new_title, url_address) {
	var new_width = 1000;
	var new_height = 550;
	var win = new Window({className: "alphacube", title: new_title,
                  width: new_width, height: new_height, zIndex:100, opacity:1,
                  url: url_address, showEffectOptions: {duration:0.5}})
	    win.showCenter();
	    return false;
}


function Help(section) {
	 q=window.open('/_admincp/help.html?action='+section, 'Help', 'scrollbars=1,resizable=1,width=450,height=400');
    }

///////////////////////////////////////////////////////////
// confirm something
function request(message)
{
  if(confirm(message)) return true;
  else return false;
}
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
// roll & expand
function expand(id)
{
  $$(id+'_opened').style.display = 'block';
  $$(id+'_closed').style.display = 'none';
}
function roll(id)
{
  $$(id+'_opened').style.display = 'none';
  $$(id+'_closed').style.display = 'block';
}
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////

// open w2 window
function w2(url, name, width, height, scroll)
{
  var w2 = window.open(url, name,
'marginheight=0,marginweight=0,toolbar=no,width='+width+',height='+height+',left=50,top=50,resizable=no,scrollbars='+scroll);
  w2.focus();
}
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
// preview
function preview(form, action, rq, width, height, scroll)
{
  var doc = document.forms[form];

  w2('/_admincp/w2.html', 'w2', width, height, scroll);
  doc.action = '/_admincp/w2.html?' + rq;
  doc.target = 'w2';
  doc.submit();
  doc.action = action;
  doc.target = '_self';

  return false;
}
///////////////////////////////////////////////////////////

var horizontal_offset="9px" //horizontal offset of hint box from anchor link

/////No further editting needed

var vertical_offset="0" //horizontal offset of hint box from anchor link. No need to change.
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
}
else{
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
}
return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth){
if ((ie||ns6) && document.getElementById("hintbox")){
dropmenuobj=document.getElementById("hintbox")
dropmenuobj.innerHTML=menucontents
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (tipwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=tipwidth
}
//alert(dropmenuobj.style.zindex);
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
dropmenuobj.style.visibility="visible"
obj.onmouseout=hidetip
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
}

function createhintbox(){
var divblock=document.createElement("div")
divblock.setAttribute("id", "hintbox")
document.body.appendChild(divblock)
}

if (window.addEventListener)
window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
window.attachEvent("onload", createhintbox)
else if (document.getElementById)
window.onload=createhintbox



/////////////////////////////////////
// Работа с формами
/////////////////////////////////////
var errs = new Array();
function imgFormClick (el,val) {
	if ((ie||ns6) && $$(el)) {
	rad_value = $$(el).value;

	if (val > 0) new_value = val;
	else if (val == 'x') new_value = rad_value;
	else new_value = rad_value == 1? '2': '1';

	new_text_value = '';

	var path=$$(el+'_img').src;
	var regexp =/_.\./g;
	path = path.replace(regexp,'_'+new_value+'.');
	$$(el+'_img').src=path;
	$$(el+'_img').alt = new_text_value;
	$$(el).value = new_value;
	}

return false;
}

function AutoFormClick (el,val) {
	if ((ie||ns6) && $$(el)) {
	rad_value = $$(el).value;

	if (val > 0) new_value = val;
	else if (val == 'x') new_value = rad_value;
	else new_value = rad_value == 1? '2': '1';

	new_text_value = '';

	var path=$$(el+'_img').src;
	var regexp =/_.\./g;
	path = path.replace(regexp,'_'+new_value+'.');
	$$(el+'_img').src=path;
	$$(el+'_img').alt = new_text_value;
	$$(el).value = new_value;
	$$('col_x').disabled = new_value == 2? true : false;
	$$('col_y').disabled = new_value == 2? true : false;
	}
}

function FormCheckInt (el,id,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $$('f'+id)) {
	value = el.value;
	if (!(/^(\d{1,3})$/.test(value))) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg == $$('f'+id).innerHTML) || !errs[id]) {

		$$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}

function FormCheckName (el,id,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $$('f'+id)) {
	value = el.value;
	if (/[\||\'|\<|\>|\"|\!|\$|\&\~\*\+]/.test(value)) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg == $$('f'+id).innerHTML) || !errs[id]) {

		$$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}

function FormCheckEmpty (el,id,len,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $$('f'+id)) {
	value = el.value;
	if (el.value.replace(/ /gi,"").length < len) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg == $$('f'+id).innerHTML) || !errs[id]) {
		$$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}

function FormCheckEmail (el,id,showerr,elfocus,errmsg) {
	if ((ie||ns6) && el && $$('f'+id)) {
	value = el.value;
	if (!(/^[a-zA-Z0-9\_\-]{2,32}[\@][a-zA-Z0-9\-]{2,32}[\.][a-zA-Z0-9]{2,4}$/.test(value))) {
		el.className = 'inp_text_err';
		errs[id] = 1;
		if (showerr == 1) {
			$$('f'+id).innerHTML = errmsg;
		}
		if (elfocus == 1) {
			el.focus();
		}
	}
	else if ((errs[id] == 1 && errmsg == $$('f'+id).innerHTML) || !errs[id]) {

		$$('f'+id).innerHTML = '';
		el.className = 'inp_text_hover';
		errs[id] = 0;
		if (elfocus == 1) {
			el.focus();
		}
	}
	}
}


function CheckAllow (el, name, table, id, errmsg, cid) {
  var req = new JsHttpRequest();
	value = el.value;
  	req.open(null, '/_admincp/_sections/_modules/users/files/_ajax/check_regname.php', true);
	var data = { 'Name': name, 'Value': value, 'Table': table, 'id': cid };
    	req.send(data);

    	req.onreadystatechange = function() {
		if (req.readyState == 4) {

		//$$('debug').innerHTML = req.responseText;

		if (req.responseJS.status>0) {
			$$('f'+id).innerHTML=errmsg;
			el.className = 'inp_text_err';
			errs[id] = 1;
			el.focus();
		}
		else if ((errs[id] == 1 && errmsg == $$('f'+id).innerHTML) || !errs[id]) {

			$$('f'+id).innerHTML = '';
			errs[id] = 0;
			el.className = 'inp_text_hover';
		}

	}
    }
}


function removeElement(parent_name,child_name) {
  var d = $$(parent_name);
  var olddiv = $$(child_name);
  d.removeChild(olddiv);
}

function removeElement2(parent_name,child_name) {
  var d = window.parent.parent.$$(parent_name);
  var olddiv = window.parent.parent.$$(child_name);
  d.removeChild(olddiv);
}



function resetTable() {

        var table = $$("TheTable");
        if(table) table.parentNode.removeChild(table);

        table     = document.createElement("table");
        var tr    = document.createElement("tr");
        var thead = document.createElement("thead");
        var tbody = document.createElement("tbody");
        var th    = document.createElement("th");
        var trc   = tr.cloneNode(true);
        var thc;

        table.id = "TheTable";
        table.className = "sortable-onload-2 rowstyle-alt no-arrow paginate-10";
        table.cellspacing = table.cellpadding = table.style.border = "0";
		table.style.width = "100%";

        document.getElementsByTagName('body')[0].appendChild(table);
        thead.appendChild(trc);
        table.appendChild(thead);
        table.appendChild(tbody);
        table = null;

        var h = [["ID","sortable-numeric"], ["Превью","sortable-numeric"] ,["Позиция","sortable-numeric"],["Заголовок","sortable-text"],["Описание","sortable-text"],["Виден на сайте","sortable-text"],["Действие","sortable"]];
        for(var j = 0; j < 7; j++) {
                thc = th.cloneNode(false);
                trc.appendChild(thc);
                thc.className = h[j][1];
                thc.appendChild(document.createTextNode(h[j][0]));
                thc = null;
        };

        trc = thead = null;
        tbody = null;

        fdTableSort.init();
        return false;
}


function FormCheckErr (cnt) {
	if (ie||ns6) {
		for (i=1; i <= cnt; i++) {

        	if (errs[i] == 1) {

        		$$('p'+i).focus();
        		return false;
        	}
		}
	}
return true;
}

function clearform(frm){

    for (var i=0;i<frm.length;i++) {
      var el=frm.elements[i];
      //if (el.type=="file") { el.reset(); continue; }
      if (el.type=="checkbox" || el.type=="radio") { el.checked=0; continue; }
      if ((el.type=="text") || (el.type=="textarea") || (el.type == "password") || (el.type == "hidden"))
      	{
      	if (el.type == "hidden")
      		{
      		if ($$(el.id + '_img'))
      			{
      			imgFormClick(el.id, 1);
      			}
      		}
		else { el.value=""; }
      	continue;
      	}
      if ((el.type=="select-one") || (el.type=="select-multiple")) { el.selectedIndex=0; }
    }

   var count_textarea = frm.getElementsByTagName('textarea').length;
   if (count_textarea>0)
   for (var j=0; j<count_textarea; j++)
   			if ($$('mce_editor_'+j) != null) tinyMCE.execInstanceCommand('mce_editor_'+j,'mceSetContent',false,' ');

}

    function ResForm(frm){
    for (var i=0;i<frm.length;i++) {
      var el=frm.elements[i];
      if (el.type == "hidden")
      		{
      		if ($$(el.id + '_img'))
      			{
      			imgFormClick(el.id, 'x');
      			}
      		}
      	continue;
      	}
    }

function reset_editors(frm){
   if (frm == null) return false;
   var count_textarea = frm.getElementsByTagName('textarea').length;
   if (count_textarea>0)
   for (var j=0; j<count_textarea; j++)
    	if ($$('mce_editor_'+j) != null) tinyMCE.execInstanceCommand('mce_editor_'+j,'mceSetContent',false,' ');

}


function create_element(type, name) {
  var element;
  try { element = document.createElement('<'+type+' name="'+name+'">'); }
  catch (e) { }

  if (!element || !element.name) {
	    element = document.createElement(type)
	    element.name = name;
	  }
 return element;
}

/*
Первый параметр функции - строка для обработки.
Второй параметр функции - символы которые подлежат удалению.
При отсутствии второго параметра - функция удалит следующие спецсимволы:

(ASCII 32 (0x20)), пробел.
(ASCII 09 (0x09)), табуляцию.
(ASCII 10 (0x0A)), символ перевода строки.
(ASCII 13 (0x0D)), символ возврата каретки.
(ASCII 00 (0x00)), нулевой символ.
(ASCII 11 (0x0B)), вертикальную табуляцию.

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.

*/
// Функция trim удаляет пробелы
// в начале и в конце строки
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}




// групповые функции
function get_check_value(body,name){
	var values = '';
    if ($$(body)==null) { close_message('error', 'Неверный параметр'); return false; }

    thisCheckBoxes = $$(body).getElementsByTagName('input');
		for (i = 0; i < thisCheckBoxes.length; i++) {
			if (thisCheckBoxes[i].name == name && thisCheckBoxes[i].checked) values += thisCheckBoxes[i].value+',';
		}
	if (values.length>0) values = values.slice(0,-1);
    else { close_message('info', 'Необходимо выбрать хотя бы один элемент!'); return false; }

return values;
}

function colorize(tr, input){
	if (tr && input) {
		//var oldClassName = tr.className;
		//tr.className = (input.checked ? 'select' : 'noSelect');
		 // tr.style.backgroundColor = (input.checked ? '#FBCEF1' : '#eff9d0');
		//if (oldClassName.indexOf("noread")!=-1) tr.className = tr.className + ' noread';
	}
}

function check_one(e, main){
   if (e && $$(main)) {
       if ($$(main).checked == true && e.checked == false) $$(main).checked = false;
   }
}

function check_all(e,body,name){
        if ($$(body)==null) { close_message('error', 'Неверный параметр'); return false; }
		thisCheckBoxes = $$(body).getElementsByTagName('input');
		for (i = 0; i < thisCheckBoxes.length; i++)
			if (thisCheckBoxes[i].name == name)	{
					thisCheckBoxes[i].checked = e.checked;
					//colorize($$(thisCheckBoxes[i].id.replace('inp_','')), thisCheckBoxes[i]);
					}
}

function check_value(value,body,name,main_id){
        if (main_id == undefined) main_id = 'mainCheck';
        if ($$(body)==null) { close_message('error', 'Неверный параметр'); return false; }
		thisCheckBoxes = $$(body).getElementsByTagName('input');
		for (i = 0; i < thisCheckBoxes.length; i++)
			if (thisCheckBoxes[i].name == name)	{
					if (thisCheckBoxes[i].disabled == false) thisCheckBoxes[i].checked = value;
					//colorize($$(thisCheckBoxes[i].id.replace('inp_','')), thisCheckBoxes[i]);
					}
		if ($$(main_id)) $$(main_id).checked = value;
}


function change_menu_visible(cookie_name, menu_index){
     if (cookie_name==undefined || menu_index==undefined) return false;

	 if ($$('masterNavLinks'+menu_index) != null && $$('masterNavh'+menu_index) != null) {
			 $$('masterNavh'+menu_index).className = ($$('masterNavh'+menu_index).className=='inactive') ? 'active' : 'inactive';
	 		 $$('masterNavLinks'+menu_index).style.display = ($$('masterNavLinks'+menu_index).style.display=='none') ? '' : 'none';
	 		 } //else close_message('error', 'Ошибка');

         var lcol_menu = getCookie('lcol_menu');
         if (lcol_menu == null || lcol_menu == '') lcol_menu = '2,2,2,2,2';

            var values = lcol_menu.split(',');
            var new_values = ''; var j=0;
         	if (values.length > 0) for (var i=0; i<values.length; i++) if (values[i]>0) {
         			j++;
         			new_values += (j==menu_index) ? ( (values[i]==2) ? 1 : 2) : values[i];
         			new_values += ',';
         			}

         if (new_values) {
         	new_values.substring(0,new_values.length-1);
         	addCookie(cookie_name, new_values, 30, '/');
         	}

         	//alert(values + ' == ' + new_values);
}

////////////////////////////
// <<<<< РАБОТА С COOKIE  //
////////////////////////////
function addCookie(szName,szValue,dtDaysExpires,cPath)
{
   var dtExpires = new Date();
   var dtExpiryDate = "";

   dtExpires.setTime(dtExpires.getTime() + dtDaysExpires * 24 * 60 * 60 * 1000);
   dtExpiryDate = dtExpires.toGMTString();
   document.cookie = szName + "=" + szValue + "; path=" +cPath+ "; expires=" + dtExpiryDate;
}

function getCookie(name) {
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        if (cookieStartIndex == -1) return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT"
	}
}
////////////////////////////
// РАБОТА С COOKIE >>>>>> //
////////////////////////////


function menu_visible(id){
if ($$('img_'+id)!=null && $$('menu_'+id)!=null){
	var img = $$('img_'+id);
	var menu = $$('menu_'+id);

	img.src = (/minus.gif/.test(img.src)) ? '_design/img/plus.gif' : '_design/img/minus.gif';
	menu.className = (menu.className == 'open') ? 'close' : 'open';

   // get_menu();
}

}

content_id = 'main_body';

function tabs(id, e){
   e.blur();
   var lis = e.parentNode.parentNode.getElementsByTagName('li');
   var li_active = e.parentNode;
   if (lis.length>0) for (var i=0; i<lis.length; i++) {
   		lis[i].className = (lis[i].innerHTML == li_active.innerHTML) ? 'current': '';
   		}


	var content = $$(content_id);
 	var pettern = new RegExp('^http\:\/\/'+location.host,'i');
	var path = e.href.replace(pettern, '');

	if (content!=null) {

		show_message('Загрузка данных');

	  	var req = new JsHttpRequest();
		req.open(null, '/js/_ajax/change_content.php', true);
		var data = { 'id': id, 'path': path };
    	req.send(data);

		req.onreadystatechange = function() {
			if (req.readyState == 4) {

			//$$('debug').innerHTML = req.responseText;

			//**** СОДЕРЖИМОЕ ****//
			var html = req.responseJS.html;
			content.innerHTML = (html) ? html : '';

			//**** ЗАГОЛОВОК СТРАНИЦЫ ****//
			document.title = req.responseJS.MetaTitle;

			//**** НАВИГАЦИОННАЯ ЛИНИЯ ****//
			//var navigationLine = req.responseJS.navigationLine;
			//if (navigationLine && $$('navigation')!=null) $$('navigation').innerHTML = navigationLine;
			//**** МЕНЮ САЙТА ****//
			//var menu = req.responseJS.menu;
			//if (menu && $$('menu')!=null) $$('menu').innerHTML = menu;
            initLightbox();
			close_message();
			}


		}
	} else if (path) location.href = ''+path+'';


   return false;
}



/* ГРУППЫ ПОЛЕЙ */

function load_fields(type){
  var req = new JsHttpRequest();
  	req.open(null, '/_admincp/_sections/_modules/category/files/_ajax/catalog/load_catalog_fields.php', true);
	var data = { 'id': type };
        req.send(data);
	show_message('Загрузка данных');

    req.onreadystatechange = function() {
		if (req.readyState == 4) {
		var massiv = new Array();
		    massiv = req.responseJS.mas;
		if (massiv.length > 0) {
			$$('tr_catalog_fields').style.display = '';
			loadValues(massiv);
			if ($$('edit_catalog')) $$('edit_catalog').href = 'main.html?action=catalog_types&do=rq&id='+type;
			}
		else {
			$$('tr_catalog_fields').style.display = '';
			var select = $$('catalog_fields');
	 		select.length = 0;
	 	    	var option = document.createElement('option');
		 	option.value = 0;
	    	        option.innerHTML = 'Нет полей в группе';
			select.appendChild(option);
		        }

		close_message();
		}
    }
}


function load_field_types(current_id, type_for){
  var req = new JsHttpRequest();
  	req.open(null, '/_admincp/_sections/_modules/category/files/_ajax/catalog/load_catalog_types.php', true);
	var data = { 'id': 'all', 'type_for' : type_for};
        req.send(data);
	show_message('Загрузка данных');

    req.onreadystatechange = function() {
		if (req.readyState == 4) {
		var ids = new Array();
		var names = new Array();
		    names = req.responseJS.names;
		    ids = req.responseJS.ids;
		var display = 'none';

		if (ids.length > 0) {
			var select = $$('type_id');
    		    select.length = 1;

     		  for (i = 0; i<ids.length; i++) {
	 	    		var option = document.createElement('option');
         		 	option.value = ids[i];
					if (ids[i] == current_id) {
						option.selected = true;
						display = '';
					}

		    	option.innerHTML = names[i];
				select.appendChild(option);
	       	   }
			  if (display == 'none') $$('tr_catalog_fields').style.display = 'none';


		}
		else $$('tr_catalog_fields').style.display = 'none';

		close_message();
		}
    }
}

///// 2 ФУНКЦИИ НЕОБХОДИМЫЕ ДЛЯ СОРТИРОВКИ изображений/////
function sortImagePrepareData(tdNode, innerText) {
        var img = tdNode.getElementsByTagName('img');
        return img.length ? img[ 0 ].src : "";
}
function sortImage(a, b) {
        // Get the data for the current column from the
        // two arrays passed in as arguments like so…
        var aa = a[fdTableSort.pos];
        var bb = b[fdTableSort.pos];

        // Sort the data
        if(aa == bb) return 0;
        if(aa < bb)  return -1;
        return 1;
}
function loadValues(values){
   	var select = $$('catalog_fields');
 		  select.length = 0;

     		  for (i = 0; i<values.length; i++) {
	 	    		var option = document.createElement('option');
		 	        var cnt = (select.getElementsByTagName("option").length)+1;
         		 	option.value = cnt;
		    	        option.innerHTML = values[i];
				select.appendChild(option);
	       	   }

}


/* ГРУППЫ ПОЛЕЙ - END */
