function init_menu ()
{
	var menus = $$('ul.submenu');

	for(var i = 0; i < menus.length; i++)
	{
		DynarchMenu.setup(menus[i].id, { vertical: true, shadows:null });
	}
}

function showhide (el)
{
	el = Element.extend(el);
	var li = Element.extend(el.parentNode);
	if (li.hasClassName('q') == false)
	{
		li.toggleClassName('h');
	}
}


var Slider = {};
Slider.doit = function(id)
{
	var duration = 0.5;
	if (Slider['_' + id] === true)
	{
		Effect.SlideUp(id, { duration: duration });
		Slider['_' + id] = false;
	}
	else
	{
		Effect.SlideDown(id, { duration: duration });
		Slider['_' + id] = true;
	}
	return;
};

var Calculator = {};
Calculator.calc = function (num)
{
	var cal = Calculator[num];

	var id = 'calculator_' + num;

	var f = $(id + '_form');

	var count = parseInt( f.count.value );
	var entry = f.entry.value;

	var res1 = 0;
	var res2 = 0;

	if ( ! isNaN(count) && count > 0 && ( cal.max_count == 0 || count <= cal.max_count ))
	{
		if (cal.block_count > 1)
		{
			count = (
				parseInt( count / cal.block_count )
					+ ( (count % cal.block_count ) ? 1  : 0)
				) * cal.block_count;
		}

		var price_i = -1;

		for(var i = 0; i < cal.prices.length; i++)
		{
			if (cal.prices[i][0] > 0 && count >= cal.prices[i][0])
				price_i = i;
		}

		if (price_i >= 0 && typeof cal.prices[price_i][entry] != 'undefined' && cal.prices[price_i][entry] > 0)
		{

			res1 = count * cal.prices[price_i][entry];
			res2 = cal.block_count * cal.prices[price_i][entry];

			if (cal.price_for > 1)
			{
				res1 = res1 / cal.price_for;
				res2 = res2 / cal.price_for;
			}

			if (/\./.test(res1))
			{
				res1 = res1.toFixed(2);
			}
			if (/\./.test(res2))
			{
				res2 = res2.toFixed(2);
			}
		}
	}

//	$(id + '_result0').update( str  );

	if ( $(id + '_result1') )
		$(id + '_result1').update( res1 > 0 ? ( res1 + ' руб.' ) : ( count > 0 ? '<em>звоните</em>' : '--' )  );

	if ( $(id + '_result2') )
		$(id + '_result2').update( res2 > 0 ? ( res2 + ' руб.' ) : ( count > 0 ? '<em>звоните</em>' : '--' )  );

	return;
}

Calculator.draw = function (num, price_table)
{
	if (Calculator.init(num, price_table) === false)
	{
		return;
	}

	var cal = Calculator[num];

	var id = 'calculator_' + num;
	var html = '<p><a href="#" onclick="Slider.doit(\'' + id + '\'); return false;">[ калькулятор ]</a></p>';

	html += '<div id="' + id + '" class="calculator" style="display: none;"><div>';

	html += '<form id="' + id + '_form"><div class="border"><table><tr><td class="border"><table class="tab2">';
	html += '<tr><th>введите тираж</th><td><input type="text" class="input" name="count" value="" autocomlete="off" size="10" onKeyDown="Calculator.calc(' + num + ');" onKeyUp="Calculator.calc(' + num + ');" /></td><tr>';
	html += '<tr><th>' + ( cal.entries_title || 'вариант' ) + '</th><td><select name="entry" class="select" onchange="Calculator.calc(' + num + ');" onKeyDown="Calculator.calc(' + num + ');" onKeyUp="Calculator.calc(' + num + ');">';
	
	for(var i = 0; i < cal.entries.length; i++)
	{
		html += '<option value="' + ( i + 1 ) + '">' + cal.entries[i] + '</option>';
	}
	
	html += '</select></td><tr>';
	
//	html += '<tr><th>реальное кол-во</th><td id="' + id + '_result0">--</td><tr>';
	html += '<tr><th>стоимость тиража</th><td id="' + id + '_result1">--</td><tr>';
	html += '<tr><th>стоимость блока</th><td id="' + id + '_result2">--</td><tr>';

	html += '</table></td></tr></table></div></form>';
	
	html += '</div></div>';

	document.write(html);

	Calculator.calc(num);

	return;
}

Calculator.init = function (num, table)
{
	Calculator[num] = {
		'block_count' : table.block_count,
		'price_for' : table.price_for,
		'entries_title' : 'позиция',
		'entries' : [],
		'prices' : [],
		'max_count' : 0
		};

	var cal = Calculator[num];

	var rc = false;

	var allowed_cols = {};
	for(var i = 0, v, t, m; i < table.maxy; i++)
	{
		for(var j = 0; j < table.maxx; j++)
		{
			v = (typeof table.table[i] != 'undefined' && typeof table.table[i][j] != 'undefined') ? table.table[i][j] : '';
			v = v.replace(/^\s+/, '').replace(/\s+$/, '');

			if (i == 0 && j == 0)
			{
				// заголовок
				t = v.split(/\s*\/+\s*/);
				cal.entries_title = t[0];
			}
			else if (i == 0)
			{
				if (v.substr(0, 1) == '>')
				{
					v = v.substr(1);
					cal.max_count = parseInt(v);
				}
				else if (/цена/.test(v))
				{
					// просто колонка с ценой
					allowed_cols[j] = cal.prices.length;
					cal.prices.push( [ 1 ] );
				}
				else if (/^\d+$/.test(v) && v != '0')
				{
					// колонки с кол-вом
					allowed_cols[j] = cal.prices.length;
					cal.prices.push( [ parseInt(v) ] );
				}
			}
			else if (1 || v != '')
			{
				if (j == 0)
				{
					cal.entries.push(v);
				}
				else if (typeof allowed_cols[j] != 'undefined')
				{
					v = v.replace(',', '.');
					v = parseFloat(v);
					if (isNaN(v)) v = 0;
					cal.prices[allowed_cols[j]].push( v );
					rc = true;
				}
			}
		}
	}

/*
	for(var i = 0; i < Calculator.prices.length; i++)
	{
		for(var j = 0; j < Calculator.prices[i].length; j++)
		{
			document.write(Calculator.prices[i][j] + ' : ');
		}
		document.write('<br />');
	}
*/

	return rc;
}

var ColorSelector = {
	'prefx' : 'color-select-',
	'form_id_mask' : 'entry_form_',
	'tables' : {},
	'active': null
};

ColorSelector.set_colors = function (tab_id, colors)
{
	if (colors && colors.length > 0)
	{
		ColorSelector.tables[tab_id] = {
			'colors' : colors,
			'descriptions': {}
			};
	}
}

ColorSelector.init = function ()
{
	var r = RegExp( '^' + ColorSelector.prefx + '([0-9]+)-([0-9]+)' ), t, i, f;

	$$('div').each(function (el) {
		if ( (t = r.exec(el.id)) && typeof(ColorSelector.tables[t[1]]) != 'undefined')
		{
			el.setStyle({ 'position': 'relative' })
				.addClassName(ColorSelector.prefx + 'container')
				.insert( new Element('div', { 'id': ( el.id + '-button' ), 'class' : 'color-button', 'title': 'выберите цвет', 'style': 'position: relative;' }).observe('click', function (ev) { ColorSelector.show_colors(ev); }) )
				.insert( new Element('div', { 'id': ( el.id + '-selector' ), 'class' : 'color-selector', 'style': 'display: none; position: absolute; z-index: 100;' }) );

			f = $( ColorSelector.form_id_mask + t[1] );
			i = f[ 'description_' + t[1] + '_new' + t[2] ];
			i.id = el.id + '-description';

			ColorSelector.tables[t[1]]['descriptions'][ i.id ] = i.title;
			ColorSelector._select_color(t[1], t[2], -1);
		}
		});

	Event.observe(document.body, 'click', function (event) {
//			if ( ! $(event.element()).up('.' + ColorSelector.prefx + 'container'))
		if ( ! ColorSelector._up(event.element(), ColorSelector.prefx + 'container'))
		{
			ColorSelector.hide_colors();
		}
		});
}

ColorSelector._up = function (el, clss, tag)
{

	while ( (el = el.up()) && el != document)
	{
		if ( (clss && el.hasClassName(clss)) || (tag && el.tagName.toLowerCase() == tag))
		{
			return true;
		}
	}

	return false;
}

ColorSelector.gen_colors_block = function (tab_id, inp_id, filtr)
{
	var block = new Element('ul');

	var filtr_vars = filtr.toLowerCase().split(/\s*,\s*/);
	filtr_vars.push(filtr);

	var count = 0;

	for( var i = 0, l =ColorSelector.tables[tab_id]['colors'].length, q; i < l; i++ )
	{
		q = ColorSelector.tables[tab_id]['colors'][i];

		if (filtr && q[3])
		{
			var z = q[3].toLowerCase();
			var rc = false;
			for(var j = filtr_vars.length - 1; j >= 0; j--)
			{
				if (z == filtr_vars[j])
				{
					rc = true;
					break;
				}
			}
			if ( ! rc) continue;
		}

		block.insert(
			new Element('li', {
					'id': ( ColorSelector.prefx + tab_id + '-' + inp_id + '-color-' + i ),
					'class': 'color-' + i
					}).update(
				q[1] + ' ' +
				q[2]
				)
				.observe('click', function (ev) { ColorSelector.select_color(ev); })
				.observe('mouseover', function (event) { event.element().toggleClassName('active'); } )
				.observe('mouseout', function (event) { event.element().toggleClassName('active'); } )
			);
		count++;
	}

	if (count == 0)
	{
		block = new Element('span').update('- нет вариантов -');
	}

	return block;
}

ColorSelector._select_color = function (tab_id, input_id, color_id)
{
	var tab = ColorSelector.tables[tab_id];
	var img, descr = '';

	if (color_id < 0)
	{
		img = '<img src="/uploads2/image/materials/mat_select.gif" wdith="15" height="15" />';
	}
	else
	{
		img = tab['colors'][color_id][1];
		descr = tab['colors'][color_id][2].toLowerCase();
	}

	$( ColorSelector.prefx + tab_id + '-' + input_id + '-button' ).update(img);

	var did = ColorSelector.prefx + tab_id + '-' + input_id + '-description';
	$(did).value = tab['descriptions'][ did ];

	if (descr != '')
	{
		$(did).value += ', ' + descr;
	}
}

ColorSelector.select_color = function (event)
{
	var r = RegExp( '^color\-([0-9]+)$' );
	var el = event.findElement('li');
	var t = ColorSelector._parse_id(el.id);

	ColorSelector._select_color(t[0], t[1], t[3]);

// 	$w(el.className).each(function (clss) {
// 		if (t = r.exec(clss))
// 		{
// 			if (el = $(event.element()).up('.color-selector'))
// 			{
// 				var q = ColorSelector._parse_id(el.id);
// 				ColorSelector._select_color(q[0], q[1], t[1]);
// 			}
// 		}
// 		})

	ColorSelector.hide_colors();
}

ColorSelector.show_colors = function (event)
{
	ColorSelector.hide_colors();

	var parent = event.findElement('div');

	var q = ColorSelector._parse_id(parent.id);
	var sid = parent.id.replace('-button', '-selector');

	ColorSelector.active = sid;

//	$(sid).setStyle({
//			'left': ( parent.getWidth() + 1 ) + 'px',
//			'top': '1px'
//			});

	var tr = $(sid), filtr;
	while( tr = tr.parentNode )
	{
		if (tr.tagName == 'TR') break;
	}
	
	if (tr)
	{
		filtr = $(tr).firstDescendant().innerHTML.toString();
	}

	$(sid).update(ColorSelector.gen_colors_block(q[0], q[1], filtr)).show();
}

ColorSelector.hide_colors = function ()
{
	if (ColorSelector.active)
		$(ColorSelector.active).hide();
}

ColorSelector._parse_id = function (id)
{
	var t = id.replace(ColorSelector.prefx, '').split('-');

	if (typeof(t[0]) == 'undefined') t[0] = '';
	if (typeof(t[1]) == 'undefined') t[1] = '';

	return t;
}

document.observe('dom:loaded', ColorSelector.init);
