// HI-LOAD JS (MAIN)

var const_tip_info_timeout		= 5; // Секунды для дефолтного отображения сообщений
var const_tip_warning_timeout	= 10; // Секунды для дефолтного отображения предупреждения
var const_tip_error_timeout		= 15; // Секунды для дефолтного отображения ошибок
var var_tip						= 0; // Начальный номер инфо-блока, НЕ МЕНЯТЬ!!!

$(document).ready(function() {
	$('#warning').click(function(){
		$(this).hide();
	});

	// Добавляем рекламный счетчик
	$('.ads').live('click',function(){
		$.ajaxq('show', {
			type: 'post',
			url: '/tools/ads/',
			data:
			{
				name:	$(this).attr('rel')
			}
		});
	});

	$('body').append('<div id="tips"></div>'); // Создаем информационный блок

	// Добавляем загрузчик
	$(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();
	$('a[rel="lightboxes"]').live('click',function(){
		$.fn.colorbox({
			href:	$(this).attr('href'),
			open:	true
		});
		return false;
	});

	// Вешаем обработчики для всех AJAX запросов
	$().ajaxError(
		function() {
			ShowTip('error', mess_error);
	});

	// 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 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 ShowBlock(obj,text)
{
	$('#' + obj).html(text);
	$('#' + obj).fadeIn(500);
	var timeout = (text.length > 100) ? 20000 : 5000;
	eval('setTimeout(function() { $(\'#' + obj + '\').hide(); }, ' + timeout + ');');
}

function ShowTip(type, text, time) // Отображаем 'высячее' сообщение
{
	if (time != -1)
	{
		switch (type){
			default:
			case 'info':
				if (!time) { time = const_tip_info_timeout; }
			break;
			case 'warning':
				if (!time) { time = const_tip_warning_timeout; }
			break;
			case 'error':
				if (!time) { time = const_tip_error_timeout; }
			break;
		}
	}

	var_tip++;
	$('<div class="' + type + '" id="tip' + var_tip + '">' + text + '</div>').appendTo('#tips').show('fast').click(function(){ $(this).hide('fast') }).wrap('<a href="JavaScript:{}"></a>');
	if (time > 0) {
		eval('setTimeout(function() { $(\'#tip' + var_tip + '\').hide(\'slow\') }, (time*1000));');
	}
}

// Валидатор 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':
			ShowTip('error', mess_error);
		break;
		case 'error':
			ShowTip('error', 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 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()
{
	good_id = $(this).attr('rel');
	ShowLoader();
	$.ajaxq('basket', {
		type: 'post',
		url: '?ajax',
		dataType: 'html',
		data:
		{
			id				:good_id,
			how				:$('#how'+$(this).attr('rel')).val(),
			variant_id		:$('#variant'+$(this).attr('rel')).val(),
			variant_text	:$('#variant'+$(this).attr('rel')+' option:selected').text(),
			control			:'basket',
			action			:'add'
		},
		success: function(data) {
			$('#basket').html(data);
			ShowTip('info','<b>' + mess_good_added + '</b>: ' + $('#good_'+good_id).text());
		},
		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();
		}
	});
}

// Навигация по комментариям
function doCommentsPage(start)
{
	if (!start) {
		ShowLoader();
	}
	$.ajaxq('comments', {
		type: 'post',
		dataType: 'html',
		data:
		{
			id	:const_comment_id,
			who	:const_comment_module,
			page:var_comment_page
		},
		url: '/comments/',
		success: function(data) {
			$('#comments').html(data);
		},
		complete: function() {
			if (!start) {
				$.scrollTo($('#comments'),1000);
				HideLoader();
			}
		}
	});
	return false;
}

// Оценка материала
function doRate(module,id,value)
{
	$('#rate').rater('/tools/rate/',{
		module:		module,
		id:			id,
		maxvalue:	5,
		style:		'medium',
		curvalue:	value,
		onStart:	ShowLoader,
		onFinish:	HideLoader,
  		onData:		function(data){ $('#votes').text(data.votes); }
	});
}
