//СОБЫТИЯ
$(function(){
	$.datepicker.setDefaults({
		firstDay: 1,
		dateFormat: 'yy-mm-dd',
		dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
		dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
		monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
		duration: 'fast',
		changeYear: true
		
	});
	$(".prod").fancybox({
		"scrolling"  : "no",
		"titleShow"  : false
	});
	
	
	
	$('.fancy').fancybox();
	
	// FEEDBACK
	$(".feedback").fancybox({
		'scrolling'  : 'no',
		'titleShow'  : false
	});
	
	//SUBSCRIBE
	$('#subscribe-add').click(function(){
		var vars = {
			ru : {
				errors : {
					emptyMail : 'Введите e-mail',
					wrongMail : 'E-mail некорректен'
				},
				loading : 'Загрузка',
				enter : 'Подписаться'
			},
			en : {
				errors : {
					emptyMail : 'Enter e-mail',
					wrongMail : 'E-mail is incorrect'
				},
				loading : 'Loading',
				enter : 'Subscribe'
			}
		};
		var that = this;
		var el = $('#subscribe-mail');
		var val = el.val();
		var msg = [];
		if( val=='' || val==el.attr('title') ) msg.push(vars[_LANG_].errors.emptyMail);
		else if( !val.match(/^[\d\w\.-]+@([\d\w-]+)((\.[\w\d-]+)+)?\.\w{2,6}$/) ) msg.push(vars[_LANG_].errors.wrongMail);
		
		if(msg.length>0){
			alert(msg.join("\n"));
			return false;
		}
		$(this).text(vars[_LANG_].loading).attr('disabled', 'disabled');
		$.get(ajaxFile, {go:'subscribe_add', mail:val}, function(html){
			$(that).text(vars[_LANG_].enter).removeAttr('disabled');
			alert(html);
		});
	});
	
	//AUTH
	$('#auth-button').click(function(){
		var vars = {
			ru : {
				errors : {
					emptyMail : 'Введите e-mail',
					wrongMail : 'E-mail некорректен',
					emptyPass : 'Введите пароль'
				},
				loading : 'загрузка..',
				enter : 'войти'
			},
			en : {
				errors : {
					emptyMail : 'Enter e-mail',
					wrongMail : 'E-mail is incorrect',
					emptyPass : 'Enter password'
				},
				loading : 'loading..',
				enter : 'enter'
			}
		};
		var that = this;
		var msg = []
		var mail = $('#input-login').val();
		
		if(mail=='E-mail' || mail=='') msg.push(vars[_LANG_].errors.emptyMail);
		else if(!mail.match(/^[\d\w\.-]+@([\d\w-]+)((\.[\w\d-]+)+)?\.\w{2,6}$/)) msg.push(vars[_LANG_].errors.wrongMail);
		
		var p = $('#input-pass').val();
		if(p=='Пароль' || p=='') msg.push(vars[_LANG_].errors.emptyPass);
		
		if(msg.length>0){
			alert(msg.join("\n"));
			return;
		}
		$(this).val('загрузка..').attr('disabled', 'disabled');
		$.getJSON('/ajax.php', {go:'auth', mail:mail, pass:p}, function(a){
			$('#auth-button').val('Войти').removeAttr('disabled');
			if(a.st!='ok'){
				alert(a.text);
				return false;
			}
			auth(a);
		});
		return false;
	});
});

$(function(){
	$('.needClear')
		 .focus(function(){
			  if(this.value==this.title) this.value='';
		 })
		 .blur(function(){
			  if(this.value=='') this.value=this.title;
		 });
});

function auth(u){
	var vars = {
		ru : {
			change : 'Изменение анкеты',
			exit : 'Выход'
		},
		en : {
			change : 'Change data',
			exit : 'Exit'
		}
	};
	
	var auth_html = [
		'<div>Здравствуйте, <strong>'+u['name']+'</strong>!</div><br>',
		'<div><a href="/'+_LANG_+'/cab/">'+vars[_LANG_].change+'</a></div>',
		'<div><a href="#выход" onclick="return exit()">'+vars[_LANG_].exit+'</a></div>'
	];
	var html = auth_html.join("\n");
	
	$('#auth-block').html(html).slideDown('fast');
	$('#auth-form').slideUp('fast');
	location.reload();
}

function exit(){
	$.get('/ajax.php', {go:'exit'}, function(a){
		$('#auth-block').slideUp('fast');
		$('#auth-form').slideDown('fast');
		location.reload();
	});
	return false;
}

function checkSearchForm(f){
	var msg = [];
	
	if(f['what'].value=='поиск' || f['what'].value=='') msg.push('Введите слово для поиска');
	else if(f['what'].value.length<3) msg.push('Слово для поиска должно быть длиннее 3-х символов');
	
	if(msg.length>0){
		alert(msg.join("\n"));
		return false;
	}
	return true;
}

function voteIt(btn, voting_id, answer_id){
	var btn = $(btn).attr({disabled:'disabled'});
	$.get(ajaxFile, {vote:voting_id, a_id:answer_id}, function(html){
		$('#voting-backup').html( $('#voting-screen').html() );
		$('#voting-screen').html( html );
		btn.removeAttr('disabled');
		if(answer_id==false) $('#back-to-vote').show();
	});
	return false;
}

function showVoting(){
	$('#voting-screen').html( $('#voting-backup').html() );
	$('#back-to-vote').hide();
	return false;
}

function buy(id, title){
	$("<div>").attr({
		title:'Добавление в корзину'
	})
	.html('<br><h2>'+title+'</h2><br><div>Количество: <input class="digits-only" type="text" value="1" style="width:40px;"></div><br>')
	.dialog({
		modal: true,
        resizable:false,
        zIndex: 7999,
		width:300,
		buttons : {
			'Добавить' : function(){
				$('.ui-dialog-buttonpane').remove();
				var count = $(this).find('input').val();
				var div = $(this).html('<br><div align="center">Загрузка...</div><br>');				
				$.get(ajaxFile, {go:'buy', id:id, count:count}, function(text){
					div.html('<br><div align="center">'+text+'</div><br>');
				});
			}
		}
	});
	$('input.digits-only').keypress(function(e){ 
		$(this).removeClass('error');
		if(e.which!=8 && e.which!=0 && !String.fromCharCode(e.which).match(/^[0-9]$/)){ 
			$(this).addClass('error');
			return false;
		}
	});
	return false;
}
$(document).ready(function(){
    if (window.PIE) {
        $('.pie').each(function() {
            PIE.attach(this);
        });
    }
    $('.left_menu > ul > li').hover(
		function() {
			$(this).addClass("open");
			$(this).find('> div').stop(true, true);
			$(this).find('> div').fadeIn('normal');
		},
		function() {
			$(this).removeClass("open");
			$(this).find('> div').fadeOut('');
		}
	);
    $('.prod_menu').hover(
		function() {
			$(this).addClass("open");
			$(this).find('> ul').stop(true, true);
			$(this).find('> ul').slideDown('fast');
		},
		function() {
			$(this).removeClass("open");
			$(this).find('> ul').slideUp('fast');
		}
	);	
    $("#anyClass1").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
		speed: 800,
		visible: 6
    });
});
function theRotator() {
	// Устанавливаем прозрачность всех картинок в 0
	$('div#rotator ul li').css({opacity: 0.0});
 
	// Берем первую картинку и показываем ее (по пути включаем полную видимость)
	$('div#rotator ul li:first').css({opacity: 1.0});
 
	// Вызываем функцию rotate для запуска слайдшоу, 5000 = смена картинок происходит раз в 5 секунд
	setInterval('rotate()',7000);
}
 
function rotate() {	
	// Берем первую картинку
	var current = ($('div#rotator ul li.show')?  $('div#rotator ul li.show') : $('div#rotator ul li:first'));
 
	// Берем следующую картинку, когда дойдем до последней начинаем с начала
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));	
 
	// Расскомментируйте, чтобы показвать картинки в случайном порядке
	// var sibs = current.siblings();
	// var rndNum = Math.floor(Math.random() * sibs.length );
	// var next = $( sibs[ rndNum ] );
 
	// Подключаем эффект растворения/затухания для показа картинок, css-класс show имеет больший z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);
 
	// Прячем текущую картинку
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
};
 
$(document).ready(function() {		
	// Запускаем слайдшоу
	theRotator();
});

