$(function() {
	$('.menu_item').hover(function() {
		$('a:first', this).addClass('active');
		$('.sub_menu', this).show();
	}, function() {
		$('a:first', this).removeClass('active');
		$('.sub_menu', this).hide();
	});
	if($.browser.msie && $.browser.version == 6) {
		$('.sub_menu').hover(function() {
			$(this).prev().addClass('active');
			$(this).show();
		}, function() {
			$(this).prev().removeClass('active');
			$(this).hide();
		});
	}
	
	$('#mozajka_belt').css('width', ($('.img_block').length*168) + 'px');
	
	$('.mcol_item a').hover(function(){
		$(this).parents('.mcol_item').eq(0).css('z-index', '100');
		next_obj = $(this).parent().next();
		if(next_obj.get(0).tagName == "BR" || (next_obj.get(0).tagName == "DIV" && next_obj.hasClass('clear')))
			$('img.animated', this).css({zIndex:'100', borderStyle: 'solid', borderColor: '#ffffff'}).animate({width:"75px",height:"75px", top:"-12px", left:"-20px", borderWidth:"2px"}, 400);
		else
			$('img.animated', this).css({zIndex:'100', borderStyle: 'solid', borderColor: '#ffffff'}).animate({width:"75px",height:"75px", top:"-12px", left:"-13px", borderWidth:"2px"}, 400);
	}, function(){
		$(this).parents('.mcol_item').eq(0).css('z-index', '1');
		$('img.animated', this).css('z-index', '1').animate({width:"50px",height:"50px", top:"0px", left:"0px", borderWidth:"0px"}, 400);
	});

	if($('.scrollable').length)
		$('.scrollable').jScrollPane({showArrows:true, scrollbarWidth: 1, dragMinHeight:6, dragMaxHeight:6});

	var pages_num = $('#mcol_nav_num a').length;
	var mozajka_num = $('.mcol_item a').length;
	if(pages_num > 1) $('.mcol_nav_arrow.right a').show();
	if(mozajka_num > 1) $('#centr_foto #cfoto_right a').show();
	
	if($('#cfoto_place').length) {
		showLargePic($('#cfoto_place img').attr('num'));
	}
	
	$('#mcol_nav_num a').unbind('click').click(function() {
		page_num = parseInt($(this).text())-1;
		$('#mcol_nav_num a').removeClass('blue').attr('href', 'javascript:void(0);');
		$(this).addClass('blue').removeAttr('href');
		
		pos = (12*(page_num-1)+156*page_num)*-1;
		pos += 'px';

		$('#mozajka_belt').animate({left: pos}, 500);
		$('.mcol_nav_arrow a').show();
		
		if(page_num+1 == pages_num) $('.mcol_nav_arrow.right a').hide();
		if(page_num == 0) $('.mcol_nav_arrow.left a').hide();
		
		return false;
	});
	
	$('.mcol_nav_arrow.right a').unbind('click').click(function() {
		curr_page_num = parseInt($('#mcol_nav_num a.blue').text());
		next_page = curr_page_num+1;
		if(next_page-1 <= pages_num) $('#mcol_nav_num a').eq(next_page-1).click();
		return false;
	});
	
	$('.mcol_nav_arrow.left a').unbind('click').click(function() {
		curr_page_num = parseInt($('#mcol_nav_num a.blue').text());
		next_page = curr_page_num-2;
		$('#mcol_nav_num a').eq(next_page).click();
		return false;
	});
	
	$('#centr_foto #cfoto_right a').unbind('click').click(function() {
		curr_pic_num = parseInt($('#cfoto_place img').attr('num'));
		next_pic = curr_pic_num+1;
		if(next_pic > 0) $('#centr_foto #cfoto_left a').show();
		if(next_pic == mozajka_num-1) $('#centr_foto #cfoto_right a').hide();

		mozajka_page_num = next_pic/12;
		$('#mcol_nav_num a').eq(mozajka_page_num).click();
		
		next_pic_obj = $('img', $('.mcol_item a').eq(next_pic));
		if(!next_pic_obj.length) return false;

		$('#cfoto_place img').attr('num', next_pic).attr('src', "media/accessories/" + next_pic_obj.attr('pic') );
		comment_title = next_pic_obj.attr('comment_title');
		comment = next_pic_obj.attr('comment');
		if(comment_title == undefined) comment_title = "";
		if(comment == undefined) comment = "";
		
		$('#cfoto_coment span.head').html(comment_title);
		$('#cfoto_coment p').html(comment);
		
		return false;
	});
	
	$('#centr_foto #cfoto_left a').unbind('click').click(function() {
		curr_pic_num = parseInt($('#cfoto_place img').attr('num'));
		next_pic = curr_pic_num-1;
		if(next_pic > 0) $('#centr_foto #cfoto_right a').show();
		if(!next_pic) $('#centr_foto #cfoto_left a').hide();

		mozajka_page_num = Math.floor(next_pic/12);
		$('#mcol_nav_num a').eq(mozajka_page_num).click();
		
		next_pic_obj = $('img', $('.mcol_item a').eq(next_pic));
		if(!next_pic_obj.length) return false;
		
		$('#cfoto_place img').attr('num', next_pic).attr('src', "media/accessories/" + next_pic_obj.attr('pic') );
		comment_title = next_pic_obj.attr('comment_title');
		comment = next_pic_obj.attr('comment');
		if(comment_title == undefined) comment_title = "";
		if(comment == undefined) comment = "";
		
		$('#cfoto_coment span.head').html(comment_title);
		$('#cfoto_coment p').html(comment);
		
		return false;
	});
	
	$('.accesories .mcol_item a').each(function(index) {
		$(this).unbind('click').click(function() {
			next_pic = index;

			$('#centr_foto #cfoto_left a, #centr_foto #cfoto_right a').show();
			if(next_pic == mozajka_num-1) $('#centr_foto #cfoto_right a').hide();
			if(!next_pic) $('#centr_foto #cfoto_left a').hide();
			
			next_pic_obj = $('img', $('.mcol_item a').eq(next_pic));
			$('#cfoto_place img').attr('num', next_pic).attr('src', "media/accessories/" + next_pic_obj.attr('pic') );
			comment_title = next_pic_obj.attr('comment_title');
			comment = next_pic_obj.attr('comment');
			if(comment_title == undefined) comment_title = "";
			if(comment == undefined) comment = "";
			
			$('#cfoto_coment span.head').html(comment_title);
			$('#cfoto_coment p').html(comment);
		});
	});
		
	if(testURL("#item_")) {
		index = location.href.replace(/^(.)+#item_/g, "");
		$('.accesories .mcol_item a').eq(index).click();
	}

	if($("a.grouped_elements").length)
		$("a.grouped_elements").fancybox({ overlayOpacity: 0.7, padding: 4 });
	
	$('#centr.slidedown').slideDown(1500, function() { $('#content', this).fadeIn(500); });

	$('.banner_wrapper').animate({ top: '480px' }, 2000);	//width: '200px', height: '200px', borderWidth: '1px'
	$('.banner_wrapper div a').live('click', function() { $('.banner_wrapper').hide(); return false; });
	
	$('div.subscribe_block input').focus(function() {
		if($(this).val() == "Подписка на новости") $(this).val('');
	}).blur(function() {
		if($(this).val() == "") $(this).val("Подписка на новости");
	});

	if($('#activity_calendar').length)
		$('#activity_calendar').jCal({
				day:			new Date( (new Date()).setMonth( now_month ) ),
				days:			1,
				showMonths:		1,
				drawBack:		function () { return false; },
				monthSelect:	false,
				sDate:			new Date(),
				dCheck:			function (day) {
									if (day.getDay() != 6) return 'day';
									else return 'invday';
								},
				callback:		function (day, days) {
									location.href = "activity.html?" + $('div.selectedDay').attr('realid');
									return false;
								}
				});

	if($("#custom").length) $("#custom").fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 500, 'speedOut': 200, 'hideOnContentClick': true, 'onStart': $('#fancybox-right').hide() });
	
	if(document.getElementById("canvas") != null) {
		// рисуем часы
		if(!$.browser.msie) clock();
		else setTimeout(clock, 600);
		// через каждую секунду
		// часы перерисовываются
		setInterval(clock, 1000);
	}
	
	if($('#front').length) {
		docW = $(document).width();
		if($.browser.msie == true) docW -=4;
		
		docH = $(document).height();
		if($.browser.msie == true) docH -=4;
		
		winH = $(window).height();
		winW = $(window).width();
		
		$('#front').css({ 'width': docW + 'px', 'height': docH + 'px' });
		$('#front #authform').css({ 'top': ((winH-$('#front #authform').height())/2) + 'px', 'left': ((winW-$('#front #authform').width())/2) + 'px' });
		
		$(window).resize(function() {
			winH = $(window).height();
			winW = $(window).width();
			
			$('#front #authform').css({ 'top': ((winH-$('#front #authform').height())/2) + 'px', 'left': ((winW-$('#front #authform').width())/2) + 'px' });
		});
	}
	
	$('#agrbutton').live('click', function() {
		var w = ($(window).width()-400)/2;
		window.open("/agreement.html", "agreement", 'menubar=no,scrollbars=yes,status=no,toolbar=no,titlebar=no,width=400,height=200,top=200,left=' + w);
		return false;
	});
	
	$('.request_form input[type=checkbox][name=news]').live('click', function() {
		if(!$(this).is(':checked') && !$('.request_form input[type=text][name=phone]').val()) {
			$('p.error_msg').show().next().hide();
		} else {
			$('p.error_msg').hide().next().show();
		}
	});
	
	$('.request_form input[type=text][name=phone]').live('keyup', function() {
		if(!$(this).val() && !$('.request_form input[type=checkbox][name=news]').is(':checked'))
			$('p.error_msg').show().next().hide();
		else
			$('p.error_msg').hide().next().show();
	});
});

function toResize() {
	
}

function showLargePic(current_pic_num) {
	comment_title = $('img', $('.mcol_item a').eq(current_pic_num)).attr('comment_title');
	comment = $('img', $('.mcol_item a').eq(current_pic_num)).attr('comment');
	$('#cfoto_place img').attr('num', '0').attr('src', "media/accessories/" + $('img', $('.mcol_item a').eq(current_pic_num)).attr('pic') );
	$('#cfoto_coment span.head').html(comment_title);
	$('#cfoto_coment p').html(comment);
}

function testURL(url) {
	return eval("/"+url.replace(/\//g, "\\\/")+"/.test(location.href)");
}

function hasFlash() {
	var UseFlash = 0;
	if (navigator.mimeTypes != undefined && navigator.mimeTypes["application/x-shockwave-flash"] != undefined ) {
		var plugin = navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin;
		if (plugin && parseInt(plugin.description.substring(plugin.description.indexOf(".")-2))>=5)
			UseFlash = 1;
	} else {
		try{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			for (var i=3; axo!=null; i++) {
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
			}
		} catch(e) {}
		if(axo) UseFlash = 1;
	}
	return UseFlash;
}

function clock() {
  // получаем текущие дату и время
  var now = new Date();
  var sec = now.getSeconds();
  var min = now.getMinutes();
  var hr = now.getHours();
 
  // получаем контекст canvas
  var ctx = document.getElementById("canvas").getContext("2d");
 
  // сохраняем состояние
  ctx.save();
  // инициализируем холст
  ctx.clearRect(0,0,150,150);
  // рисуя в точке 0,0 фактически
  // рисуем в точке 75,75
  ctx.translate(75,75);
  // при рисовании линии в 100px
  // фактически рисуем линию в 40px
  ctx.scale(0.4,0.4);
  // начинаем вращать с 12:00
  ctx.rotate(-Math.PI/2);
 
  // инициализируем свойства рисунка
  // контуры рисуем черным
 // ctx.strokeStyle = "black";
  // заливка тоже черная
 // ctx.fillStyle = "black";
  // ширина линии 8px
 // ctx.lineWidth = 8;
  // будем рисовать по кругу
 // ctx.lineCap = "round";
 
  // начинаем рисовать часовые метки
  // сохраняем предыдущее состояние
  ctx.save();
  ctx.beginPath();
  // для каждого часа
  //for(var i = 0; i < 12; i++) {
    // поворачиваем на 1/12
  //  ctx.rotate(Math.PI/6);
    // перемещаем курсор
  //  ctx.moveTo(100,0);
    // рисуем черточку 20px
  //  ctx.lineTo(120,0);
  //}
  ctx.stroke();
  ctx.restore();
 
  // сохраняем состояние
  //ctx.save();
  // ставим ширину линии 5px
 // ctx.lineWidth = 5;
 // ctx.beginPath();
  // рисуем минутные метки
  // для каждой минуты
 // for(var i = 0; i < 60; i++) {
    // кроме тех, что совпадут
    // с часами
  //  if(i%5 != 0) {
      // перемещаем курсор
  //    ctx.moveTo(117,0);
      // рисуем черточку 3px
   //   ctx.lineTo(120,0);
  //  }
    // вращаем холст на 1/60
  //  ctx.rotate(Math.PI/30);
 // }
 // ctx.stroke();
 // ctx.restore();
 
  // сохраняем состояние
  ctx.save();
  // начинаем рисовать часовую стрелку
  // вращаем холст на текущую позицию
  ctx.rotate((Math.PI/6)*hr +
             (Math.PI/360)*min +
             (Math.PI/21600)*sec);
  // устанавливаем ширину линии 14px
  ctx.lineWidth = 6;
 
  ctx.beginPath();
  // сдвигаем курсор несколько назад
  // стобы было похоже на стрелку
  ctx.moveTo(0,0);
  // рисуем линию почти до часовых меток
  ctx.lineTo(80,0);
  ctx.stroke();
  ctx.restore();

  // сохраняем состояние
  ctx.save();
  // начинаем рисовать минутную стрелку
  // вращаем холст на текущую позицию
  ctx.rotate((Math.PI/30)*min +
             (Math.PI/1800)*sec);
  // ширина линии 10px
  ctx.lineWidth = 4;
  ctx.beginPath();
  // двигаем курсор
  ctx.moveTo(0,0);
  // рисуем линию
  ctx.lineTo(112,0);
  ctx.stroke();
  ctx.restore();
 
  // сохраняем состояние
  ctx.save();
  // начинаем рисовать секундную стрелку
  // вращаем холст на текущую позицию
  ctx.rotate(sec * Math.PI/30);
  // контур и заливка красного цвета
  ctx.strokeStyle = "#000000";
  ctx.fillStyle = "#000000";
  // ширина линии 6px
  ctx.lineWidth = 2;
  ctx.beginPath();
  // двигаем курсор
  ctx.moveTo(-30,0);
  // рисуем линию
  ctx.lineTo(120,0);
  ctx.stroke();
  ctx.restore();
 
  // сохраняем состояние
  ctx.save();
  // рисуем внешнюю окружность
  // шириной 14px
 // ctx.lineWidth = 14;
  // синим цветом
 // ctx.strokeStyle = "#325FA2";
 // ctx.beginPath();
  // рисуем окружность, отступающую
  // от центра на 142px
 // ctx.arc(0,0,124,0,Math.PI*2,true);
 // ctx.stroke();
  ctx.restore();
 
  ctx.restore();
}

