var picture, pictures, current ,next, interval;
var show_picture = function () {
	jQuery(current).css('z-index', 10);
	jQuery(next).css('z-index', 20);
	jQuery(current).fadeOut(1000);
	jQuery(next).fadeIn(1);	
	current = next;
	next = jQuery(current).next().length ? jQuery(current).next() : jQuery(pictures).eq(0);
}

jQuery(function(){
	/* auth */
	jQuery('#right_1 .in').click(function(){
		jQuery('#auth_form').toggle(); 
		jQuery('#auth_bg').toggle(); 
		return false;
	});
	jQuery('#auth_form .close_form').click(function(){
		jQuery('#auth_form').hide(); 
		jQuery('#auth_bg').hide(); 
		return false;
	});

	/* big_pictures */
/*	picture = jQuery('#big_picture .picture');
	pictures = jQuery('img', picture);
	current = jQuery(pictures).eq(0);
	next = jQuery(pictures).eq(1);
	show_picture();
	interval = setInterval('show_picture()', 10000);
*/

	/* alphabet */
	var letter = '';
	var html = '';
	
	var alphabet = jQuery("#alphabet");
	jQuery(alphabet).append('<div class="list" style="display: none;"><a href="#" class="close"><img src="/images/styles/close.gif" alt="х" /></a></div>');
	jQuery("table a", alphabet).click(function(){
		// Буковка
		letter = this.innerHTML;
		if ((jQuery('.list', alphabet).css('display') == 'none') || (jQuery('.list_arrow', jQuery(this).parent()).length == 0)){
			//формируем html-содержимое (список площадок)
			html = '<a href="#" class="close"><img src="/images/styles/close.gif" alt="х" /></a>\
			<div class="top iepng">&nbsp;</div>\
			<ul class="iepng">';
			
			if (typeof platforms == 'object' && typeof platforms[letter] == 'object') {
				// в эту строку вставляется список площадок =_=
				for (var i in platforms[letter]) {
					html += '<li><a href="' + platforms[letter][i] + '">' + i + '</a></li>';
				}
			} else {
				html += '<li>Площадок не обнаружено</li>';
			}
			html += '</ul><div class="bottom iepng">&nbsp;</div>';

			//если мы тыкнули по букве
			jQuery('.list_arrow', alphabet).remove(); 
			jQuery('.list', alphabet).hide();
			jQuery('.list', alphabet).html(html); // отображаем список
			jQuery(this).parent().append('<div class="list_arrow iepng" style="display: none;">&nbsp;</div>');
			//если мы тыкнули по букве во второй строке
			if (jQuery(this).parent().parent().parent().hasClass('tr_2')){
				jQuery('.list', alphabet).css({'bottom': 'auto', 'top': '111px'})
			} else {
				jQuery('.list', alphabet).css({'top': 'auto', 'bottom': '80px'})	
			}

			jQuery('.list', alphabet).show();
			jQuery('.list_arrow', alphabet).show();
		} else {
			//если ты тыкнули по букве второй раз подряд
			jQuery('.list_arrow', alphabet).remove(); 
			jQuery('.list', alphabet).hide();
		}
		jQuery('.close', alphabet).click(function(){
			jQuery('.list', alphabet).hide();
			jQuery('.list_arrow', alphabet).remove(); 
			return false;
		});
		return false;
	});
	
	// Календарь... Эх
	/** Функция построения календаря */
	function buildCal(m, y){
		var dim = [31,0,31,30,31,30,31,31,30,31,30,31];

		var oD = new Date(y, m - 1, 1); //DD replaced line to fix date bug when current day is 31st
		oD.od = oD.getDay() + 1; //DD replaced line to fix date bug when current day is 31st

		var todaydate = new Date() //DD added
		var scanfortoday = (y==todaydate.getFullYear() && m==todaydate.getMonth()+1)? todaydate.getDate() : 0 //DD added
		
		var drawLinks = (y > todaydate.getFullYear() || (y == todaydate.getFullYear() && (m - 1) >= todaydate.getMonth()));

		dim[1] = (((oD.getFullYear() % 100 != 0) && (oD.getFullYear() % 4 == 0)) || (oD.getFullYear() % 400 == 0)) ? 29 : 28;
		var t = '<tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th class="holiday">сб</th><th class="holiday">вс</th></tr>';
		t+='</tr><tr align="center">';
		// Хак для дат
		var flag = false;
		var nextM = 1;
		var i = (oD.od == 1) ? - 6 : 1;
		var e = (oD.od == 1) ? 35 : 42;
		for (i; i <= e; i++) {
			flag = true;
			var x = ((i - oD.od + 1 >= 0) && (i - oD.od + 1 < dim[m - 1])) ? i - oD.od + 1 + 1 : '&nbsp;';
			// даты до и после выбранного месяца
			if (isNaN(x)) {
				flag = false;
				if (i < 10) x = (m == 1 ? dim[11] : dim[m - 2]) - (oD.od - i - 2);
				else x = nextM++;
			}
			if (drawLinks && x < scanfortoday) flag = false;
			// ссылки на календарь
			t += '<td class="' + (flag && x == scanfortoday ? "active" : "") + " " + ((i) % 7 == 0 || (i) % 7 == 6 ? "holiday" : "") + '">';
			t += (flag && drawLinks) ? '<a href="/catalogue/?date='+(x<10?"0":"")+x+'.'+(m<10?"0":"")+m+'.'+y+'">'+x+'</a>' : x;
			t += '</td>';
			if (((i) % 7 == 0) && (i < 36)) t+= '</tr><tr align="center">';
		}
		return t += '</tr>';
	}
	
	function redrawMonth(selMon) {
		if (typeof selMon != 'number' || selMon < 1 || selMon > 12) {
			selMon = 1;
		}
		var html = '';
		var mName = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
		for (var i = 0; i < 12; i++) {
			html += '<option' + ((selMon - 1) == 1 ? ' selected="selected"' : '') + '>' + mName[i] + '</option>';
		}
	}
	
	// Предыдущий месяц
	var prevMonth = jQuery("div#calendar .calendar .date .prev a:eq(0)");
	// Следующий месяц
	var nextMonth = jQuery("div#calendar .calendar .date .next a:eq(0)");
	// Селект выбора месяца
	var selMonth = jQuery("div#calendar .calendar .date .month select:eq(0)");
	// Селект выбора года
	var selYear = jQuery("div#calendar .calendar .date .year select:eq(0)");
	// Таблица с календарем
	var calTable = jQuery("div#calendar .calendar table.date:eq(0)");
	// Текущий день
	var curDate = new Date();
	var curDay = curDate.getDay();
	var curMonth = curDate.getMonth();
	var curYear = curDate.getFullYear();
	
	// Обработчики событий
	prevMonth.click(function(){
		// Не меньше текущего месяца
		// Перерисовываем селекты, а затем - вызываем событие на изменения селектов
		if (selYear.val() == curYear && (selMonth.attr("selectedIndex") == (curMonth - 0))) {
			// Ничего не делаем
		} else if (selMonth.attr("selectedIndex") == 0 && selYear.val() > curYear) {
			selMonth.attr("selectedIndex", 11);
			selYear.attr("selectedIndex", (selYear.attr("selectedIndex") - 1));
		} else {
			selMonth.attr("selectedIndex", selMonth.attr("selectedIndex") - 1);
		}
		selMonth.change();
		return false;
	});
	
	nextMonth.click(function(){
		// Не больше декабря через два года
		if (selMonth.attr("selectedIndex") == 11 && selYear.attr("selectedIndex") == 2) {
			selMonth.attr("selectedIndex", 11);
		} else if (selMonth.attr("selectedIndex") == 11 && selYear.attr("selectedIndex") < 2) {
			selMonth.attr("selectedIndex", 0);
			selYear.attr("selectedIndex", (selYear.attr("selectedIndex") + 1));
		} else {
			selMonth.attr("selectedIndex", selMonth.attr("selectedIndex") + 1);
		}

		selMonth.change();
		return false;
	});
	
	selMonth.change(function(){
		// Невозможно выбрать меньше текущей даты
		if (selYear.val() == curYear && (this.selectedIndex < curMonth)) {
			// Перерисуем select выбора месяца
			this.selectedIndex = curMonth;
			calTable.html(buildCal(curMonth + 1, curYear));
			return false;
		}
		calTable.html(buildCal(selMonth.attr("selectedIndex") + 1, selYear.val()));
		return false;
	});

	selYear.change(function(){
		// Невозможно выбрать меньше текущей даты
		if (selYear.val() == curYear && (selMonth.attr("selectedIndex") < curMonth)) {
			// Перерисуем select выбора месяца
			selMonth.attr("selectedIndex", curMonth);
			calTable.html(buildCal(curMonth + 1, curYear));
			return false;
		}
		calTable.html(buildCal(selMonth.attr("selectedIndex") + 1, selYear.val()));
		return false;
	});



	//для каталога... select с датами
	/*var divDates = jQuery(".dates_tickets");
	if (divDates.length == 1){
		var dates = jQuery('.date', divDates);
		jQuery(dates).hide();
		jQuery(dates).eq(0).show();
		jQuery(divDates).prepend('<p class="choose_date"></p>');
		var chooseDate = jQuery('.choose_date', divDates);
		var select = 'Дата: <select>';
		for (var i = 0; i < dates.length; i++){
			select = select + '<option name="' + i + '">' + jQuery('h3', dates).eq(i).text() + '</option>';
		}
		select += '</select>';
		jQuery(chooseDate).html(select);
		jQuery('select', chooseDate).change(function () {
			var n = jQuery("option:selected", this).attr("name");
			jQuery(dates).hide();
			jQuery(dates).eq(n).show();
		});
	}*/



	var hideshowBlock = jQuery("#hideshow");
	jQuery('.ticket', hideshowBlock).hide();
	jQuery('.space', hideshowBlock).hide();
	/*var showtr = jQuery('tr:visible', hideshowBlock);*/
	var showtr = jQuery('tr.clickable', hideshowBlock);
	jQuery(showtr).addClass('arrow_cat').addClass('main_line');
	//for (var i = 0; i < showtr.length; i = i + 2) {jQuery(showtr).eq(i).addClass('dark');}
	jQuery(showtr).css('cursor', 'pointer');
	/*jQuery(showtr).eq(0).css('cursor', 'default');*/
	jQuery(showtr).toggle(function(){
		var next = jQuery(this).next();
		while (!jQuery(next).hasClass('space')) {
			jQuery(next).show();
			next = jQuery(next).next();
		}
		jQuery(next).show();
		jQuery(this).removeClass('arrow_cat');
	}, function(){
		var next = jQuery(this).next();
		 while (!jQuery(next).hasClass('space')) {
			jQuery(next).hide();
			next = jQuery(next).next();
		}
		jQuery(next).hide();	
		jQuery(this).addClass('arrow_cat');
	});

	jQuery('input:checkbox', hideshowBlock).click(function(){
		var first = jQuery(this).parents('tr').prevAll('tr.main_line').eq(0);
		var current = jQuery(first);
		var number = 0;
		while (!jQuery(current).hasClass('space')) {
			//alert(jQuery(current).attr('class'));
			//alert(jQuery("input:checked", jQuery(current)).length);
			if(jQuery("input:checked", jQuery(current)).length) {
				number++;
			}
			current = jQuery(current).next();
		}
		if(number) {
			jQuery(first).addClass('active_tr');		
		}
		else {
			jQuery(first).removeClass('active_tr');		
		}
	});
});
