// HI-LOAD JS (MAIN)

// Верхнее меню
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function topmenu_open()
{
	topmenu_canceltimer();
	topmenu_close();
	ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function topmenu_close()
{
	if (ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function topmenu_timer()
{
	closetimer = window.setTimeout(topmenu_close, timeout);
}

function topmenu_canceltimer()
{
	if (closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

$(document).ready(function() {
	$('#tm > li').bind('mouseover', topmenu_open);
	$('#tm > li').bind('mouseout',  topmenu_timer);

	$('#warning').click(function(){		$(this).hide();	});

	// Добавляем рекламный счетчик
	$('.ads').live('click',function(){		$.ajaxq('show', {
			type: 'post',
			url: '/tools/ads/',
			data:
			{
				name:	$(this).attr('rel')
			}
		});	});

	// Добавляем загрузчик
	$(document.createElement("div")).attr("id","overlay").click(HideLoader).appendTo("body");
	$(document.createElement("img")).attr("id","loader").attr("src","/_static/img/loading.gif").click(HideLoader).appendTo("#overlay");

	// Цепляем всем фоткам лайтбоксы
	$("a[rel='lightbox']").colorbox();

	// Вешаем обработчики для всех AJAX запросов
	$().ajaxError(
		function() {
			ShowError('warning', mess_error);
	});

	// Подгоняем картинки к размерам центральной области
	AutoSizeImages();

	// http://gsgd.co.uk/sandbox/jquery.easing.php
	$.easing.elasout = function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	};
});

// Подгонка изображений
function AutoSizeImages()
{	var work_width = parseInt($('td.center').css('width'));
	var diff_width = 50;
	var corr_width = 5;
	$('td.center img').each(function(){		var image_width = parseInt($(this).css('width'));
		if (work_width < (image_width + diff_width)) {			$(this).css('width',image_width-corr_width);
			AutoSizeImages();		}	})
}

// Проверяем поля на заполненность
function CheckForm(form,mess)
{
	var result	= true;
	var started	= false;

	$('#' + form).find('.must').each(function() {

		var $inp = $(this).next().find('input, select, textarea');
		var value = $inp.val();

		if ((value == '') || (value == null)) {
			if (started == false) { $.scrollTo($inp.parent()); $inp.focus(); started = true; }
			var error_id		= 'error_' + $inp.attr('id');
			var count_error_id	= 'count_' + error_id;

			if ($('#' + error_id).length == 0) {
				$comment = $inp.parent().parent().find('span.comment');
				if ($comment.length == 0) { $comment = $inp.parent(); }
				$('<b class="red" id="' + error_id + '">' + mess + '</b>').hide().appendTo($comment);
			}
			$('#' + error_id).fadeOut().fadeIn().fadeOut().fadeIn();

			eval('if (typeof(' + count_error_id + ') == \'undefined\') { result_count = 0; } else { result_count = ' + count_error_id + '; }');
			if (result_count == 0) {
				eval(count_error_id + ' = setTimeout(function() { $(\'#' + error_id + '\').fadeOut(); ' + count_error_id + ' = 0; }, 5000);');
			}
			result = false;
		}
	});
	return result;
}

// Отображение ошибки
function ShowError(obj,text)
{
	$('#' + obj).html(text);
	$('#' + obj).fadeIn(500);
	var timeout = (text.length > 100) ? 20000 : 5000;
	eval('setTimeout(function() { $(\'#' + obj + '\').hide(); }, ' + timeout + ');');
}

// Валидатор AJAX
function CheckData(data)
{
	var result_type	= data['type'];
	var result_data	= data['data'];
	var result_exec	= data['exec'];

	if (result_exec != '') {
		eval(result_exec);
	}

	switch (result_type) {
		default:
		case 'false':
			ShowError('warning', mess_error);
		break;
		case 'error':
			ShowError('warning', result_data);
		break;
		case 'ok':
			return result_data;
		break;
	}

	return null;
}

// Скривыем окно загрузки
function HideLoader()
{
	$('#overlay').hide();
}

// Показываем загрузчик
function ShowLoader()
{
	var window_height	= $(window).height();
	var window_width	= $(window).width();
	var window_scroll	= $(window).scrollTop();
	var maxheight		= ($(document).height() > window_height) ? $(document).height() : window_height;

	$('#loader').css('top',window_scroll + window_height/2 - 11 + 'px').css('left',window_width/2 - 63 + 'px');
	$('#overlay').css('height',maxheight + 'px').show();
}

// Просмотр обьектов
function ShowSite(who,id)
{
	$.ajaxq('show', {
		type: 'post',
		url: '/tools/show/',
		data:
		{
			id:		id,
			who:	who
		}
	});
}

// Копирование вложенного меню
function doMenuTransfer(who,ids)
{
	var sLinks = '';
    var arrIds = new Array();
	arrIds = ids.split(',');
	for(i=0;i<arrIds.length;i++)
	{
		id = arrIds[i];
		if ($('ul#menu' + id).length > 0) {
			$('ul#menu' + id + ' a').each(function(){
				sLinks += '<a href="' + $(this).attr('href') + '">' + $(this).text() + '</a>';
			});
		}
	}
	if (sLinks.length > 0) {
		sLinks += '<div class="c"></div>';
		$('#' + who).find('.links').html(sLinks);
		$('#' + who).show();
	}
}

// Копирование вложенного меню
function doShopTransfer(who,inner)
{
	var sLinks = '';
	if ($('ul#shoptree').length > 0) {
		if (inner) {			$('li[rel="shp' + inner + '"] > ul li a').each(function(){
				sLinks += '<a href="' + $(this).attr('href') + '">' + $(this).text() + '</a>';
			});
		} else {
			$('ul#shoptree > li a').not('ul li ul a').each(function(){				sLinks += '<a href="' + $(this).attr('href') + '">' + $(this).text() + '</a>';
			});
		}
	}
	if (sLinks.length > 0) {
		sLinks += '<div class="c"></div>';
		$('#' + who).find('.links').html(sLinks);
		$('#' + who).show();
	}
}

// Ускоренная навигация по страницам для пользователей
function doPage()
{
	ShowLoader();
	var link = $(this).attr('href');
	$.ajaxq('ajaxlist', {
		type: 'get',
		dataType: 'html',
		url: link,
		success: function(data) {
			$('#ajaxlist').html(data);
		},
		complete: function() {
			HideLoader();
			$.scrollTo($('#ajaxlist'),1000);
		}
	});
	return false;
}

// Добавление товара в корзину
function doBasket()
{
	ShowLoader();
	$.ajaxq('basket', {
		type: 'post',
		url: '?ajax',
		dataType: 'html',
		data:
		{
			id		:$(this).attr('rel'),
			how		:$('#how'+$(this).attr('rel')).val(),
			control	:'basket',
			action	:'add'
		},
		success: function(data) {
			$('#basket').html(data);
		},
		complete: function() {
			HideLoader();
		}
	});
}

// Меняем количество товара
function doBasketChange(id,realy)
{
	if (realy) {		var value = $('#basket'+id).val();	} else {
		var value = 0
	}

	if (id < 0)  {
		if (confirm(mess_confirm_delete_all) == false) { return true; }
	} else if (value == 0) {
		if (confirm(mess_confirm_delete_one) == false) { return true; }
	}

	ShowLoader();
	$.ajaxq('basket', {
		type: 'post',
		url: '?ajax',
		dataType: 'html',
		data:
		{
			id		:id,
			how		:value,
			control	:'basket',
			action	:'change'
		},
		success: function(data) {
			$('#basket').html(data);
		},
		complete: function() {
			HideLoader();
		}
	});
}