// encoding="utf-8"

// menu

$.mainmenuShow = function(menu) {
	if ($(menu).parent('div').hasClass('menu')) {
		var submenu = $('.menu_active').children('.submenu');
		submenu.hide();
		
		$('.menu_active').addClass('menu').removeClass('menu_active');
	}
	
	$(menu).parent('div').addClass('menu_active').removeClass('menu');
	$(menu).next('.submenu').show();
};

var count = 4;

// submenuShow($('.active', '.submenu'));
$.submenuShow = function(menu) {
	var more = menu.siblings('.more');
	while (menu.is(':hidden'))
		$.submenuRotate(more, count*2);
};

$.submenuRotate = function(menu, pos) {
	menu.prev(':hidden').after(menu.siblings(':visible'));
	menu.siblings(':lt('+ pos   +')').show();
	menu.siblings(':gt('+(pos-1)+')').hide();
};

// load
$('.more').click(function(){
	$.submenuRotate($(this), count*2);
	return false;
});

// call from player
function menushow(pmenu, smenu) {
	if (pmenu && smenu) {
		// mainmenu
		$.mainmenuShow($('#mainmenu-'+pmenu));
		
		// submenu
		$('a.active', '.submenu').removeClass('active');
		$('#submenu-'+smenu).addClass('active');
		$.submenuShow($('#submenu-'+smenu));
	}
}

// timeline

var timeline = {
	tmpl  : $('#timeline'),
	block : $('.timeline'),
	limit : 28
};

timeline.param = timeline.block.length ? timeline.block.attr('name').split(/:/) : [];

$.page = function(page, max) {
	return {
		prev: page >  1 && max >= page ? page-1 : max,
		next: page >= 0 && max >  page ? page+1 :   1
	};
};

$.timeline = function(mainmenu, submenu, page, limit) {
	var param = [];
	
	if (mainmenu) param.push('menu_id='+mainmenu);
	if (submenu ) param.push('first='  +submenu );
	if (page    ) param.push('page='   +page    );
	if (limit   ) param.push('limit='  +limit   );
	
	$.get('/timeline/video.xml?'+param.join('&'), function(xml) {
		timeline.block.html('');
		
		var pmax = $('menu', xml).attr('maxpage');
		var news = $('menu', xml).attr('name') == 'news';
		
		$('submenu', xml).each(function() {
			$('.group', timeline.tmpl)
				.clone()
				.html($(this).attr('title'))
				.appendTo(timeline.block)
			;
			$('video', $(this)).each(function() {
				var v     = $(this);
				var name  = v.attr('name').split(':');
				var title = $('title', v).text();
				
				$('.item', timeline.tmpl)
					.clone()
					.find('a')
						.attr('href', '/video/'+name[0]+'/')
						.attr('name', v.attr('name'))
						.attr('title', title)
					.end()
					.find('img')
						.attr('alt', name[0])
						.attr('title', title)
						.attr('src', $('img', v).attr('src'))
					.end()
					.find('.vtitle')
						.html(title)
					.end()
					.find('.time')
						.html(news ? v.attr('time')+' ' : '')
					.end()
					.appendTo(timeline.block)
				;
			});
		});
		
		var p = $.page(page, pmax);
		
		$('.control', timeline.tmpl)
			.clone()
			.find('.prev')
				.each(function() {
					if (page == 1) {
						$(this).remove();
					} else {
						$(this).attr('name', p.prev)
						$(this).click(function() { $.getTimeline('prev'); return false }) // live
					}
				})
			.end()
			.find('.next')
				.each(function() {
					if (page == pmax) {
						$(this).remove();
					} else {
						$(this).attr('name', p.next)
						$(this).click(function() { $.getTimeline('next'); return false }) // live
					}
				})
			.end()
			.appendTo(timeline.block)
		;
		
		$('a.video').click(function(){ return $.videoPlay($(this)) });
		
		scroll(0, 0);
	});
};

$.getTimeline = function(t) {
	var page = $('.'+t, timeline.block).length ? parseInt($('.'+t, timeline.block).attr('name')) : 1;
	
	if (!$('.next', timeline.block).length) {
		timeline.limit = Math.round((document.body.clientHeight - size)/ 51);
	}
	
	$('.loader', timeline.block).show();
	timeline.param.length == 2 ? $.timeline(timeline.param[0], timeline.param[1], page, timeline.limit) : $.timeline(0, 0, page, timeline.limit);
};

$('.prev', timeline.block).click(function() { $.getTimeline('prev'); return false });
$('.next', timeline.block).click(function() { $.getTimeline('next'); return false });

// video

$.videoPlay = function(video, flag) {
	if (!player) return true;
	
	var name = video.attr('name').split(/:/);
	if (name) {
		select_video(name[0], name[2] && (timeline.param.length == 2 || flag) ? name[2] : null);
		scroll(0, 0);
		return false;
	}
}

$('a.video').click(function(){
	var flag = $(this).parents('.news').length ? true : false;
	return $.videoPlay($(this), flag);
});

// favorite

var favorite = {
	tmpl  : $('#favorite'),
	tmplv : $('#favorite-video'),
	block : $('.favorite'),
	limit : 8
};

favorite.param = favorite.block.length ? favorite.block.attr('name') : 0;

$.shuffle = function(arr) {
	for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
	return arr;
};

$.fn.shuffle = function(limit) {
	return this.each(function(){
		var items = $(this).children();
		return (items.length) ? $(this).html(limit ? $.shuffle(items).slice(0, limit) : $.shuffle(items)) : this;
	});
};

$.favorite = function(menu) {
	var param = [];
	
	if (menu) param.push('id='+menu);
	
	$.get('/favorite/menu.xml?'+param.join('&'), function(xml) {
		$('favorite', xml).each(function() {
			var f = $(this);
			
			$('div', favorite.tmpl)
				.clone()
				.find('.title')
					.html(f.attr('title'))
				.end()
				.find('.subtitle')
					.html(f.attr('subtitle'))
				.end()
				.find('.colon')
					.each(function() { if(!f.attr('subtitle')) $(this).hide() })
				.end()
				.find('.category')
					.hide()
				.end()
				.appendTo(favorite.block)
			;
			
			$('video', $(this)).each(function() {
				var v    = $(this);
				var name = v.attr('name').split(':');
				
				$('.category_video', favorite.tmplv)
					.clone()
					.find('a')
						.attr('href', v.attr('url'))
						.attr('name', v.attr('name'))
						.attr('title', $('title', v).text())
						.click(function(){ return $.videoPlay($(this)) })
					.end()
					.find('img')
						.attr('alt', name[0])
						.attr('src', $('img', v).attr('src'))
					.end()
					.find('.vtitle')
						.html($('title', v).text())
					.end()
					.appendTo($('.category:last', favorite.block))
				;
			});
		});
		
		$('.gray:last', favorite.block).remove();
		$('.category',  favorite.block).shuffle(4).show();
		
		if ($('.main').html()) $.getTimeline('next');
	});
};

if (favorite.block.length) $.favorite(favorite.param);
if(!favorite.block.length) $.getTimeline('next');

// rss tuning

$('#create', '.tuning').click(function() {
	$('#result', '.tuning').html('Идет сохранение...');
	
	var id = ['submit=1'];
	$('input:checked', '.rssmenu').each(function() { if ($(this).attr('value')) id.push('id='+$(this).attr('value')) });
	$.post(location.href, id.join('&'), function(data) {
		$('#result', '.tuning').html(data);
	});
});

$(function() {
	// google-analytics exit hook
	$('a').click(function() {
		if ($(this).attr('href').match(/^http/)) {
			pageTracker._trackPageview('/exit/'+escape($(this).attr('href')));
		}
	});
	
	// search
	var SEARCH = {
		field  : {
			q : 'Поиск'
		},
		label  : function() {
			if (!$(this).val()) {
				$(this).val(SEARCH.field[$(this).attr('name')]);
				$(this).removeClass('active');
			} else {
				$(this).addClass('active');
			}
		},
		clean  : function() {
			var name = $(this).attr('name');
			if ($(this).val() == SEARCH.field[name]) {
				$(this).val('');
				$(this).addClass('active');
			}
		},
		submit : function() {
			$('input', $(this)).each(SEARCH.clean);
		}
	};
	
	$('input', '.search').each (SEARCH.label);
	$('input', '.search').blur (SEARCH.label);
	$('input', '.search').focus(SEARCH.clean);
	
	$('.search').submit(SEARCH.submit);
	
	// login
	var LOGIN = {
		field  : {
			email    : 'E-mail',
			password : 'Пароль'
		},
		label  : function() {
			if (!$(this).val()) {
				$(this).val(LOGIN.field[$(this).attr('name')]);
			}
		},
		clean  : function() {
			var name = $(this).attr('name');
			if ($(this).val() == LOGIN.field[name]) {
				$(this).val('');
			}
		},
		submit : function() {
			$('input', $(this)).each(LOGIN.clean);
		}
	};
	
	$('input', '.login').each (LOGIN.label);
	$('input', '.login').blur (LOGIN.label);
	$('input', '.login').focus(LOGIN.clean);
	
	$('.login').submit(LOGIN.submit);
	
	// signup
	var SIGNUP = {
		field  : {
			invite      : 'Код приглашения',
			password    : 'Пароль',
			password2   : 'Пароль еще раз',
			email       : 'E-mail',
			last_name   : 'Фамилия',
			first_name  : 'Имя',
			middle_name : 'Отчество',
			birthday    : 'Дата рождения',
			inn         : 'ИНН',
			phone       : 'Телефон'
		},
		label  : function() {
			if (!$(this).val()) {
				var o = $(this);
				if ($(this).attr('type') == 'password') {
					$(this).hide();
					o = $('input[name="'+$(this).attr('name')+'t"]').show();
				}
				o.val(SIGNUP.field[$(this).attr('name')]);
			}
		},
		clean  : function() {
			var n = $(this).attr('name').match(/(password\d?)/) || [];
			var name = n[0] || $(this).attr('name');
			
			if ($(this).val() == SIGNUP.field[name]) {
				$(this).val('');
				
				if (n[0]) {
					$(this).hide();
					$('input[name="'+name+'"]').show().focus();
				}
			}
		},
		submit : function() {
			$('input', $(this)).each(SIGNUP.clean);
		}
	};
	
	$('input', '.signup').each (SIGNUP.label);
	$('input', '.signup').blur (SIGNUP.label);
	$('input', '.signup').focus(SIGNUP.clean);
	
	$('.signup').submit(SIGNUP.submit);
	
	// forgot
	var FORGOT = {
		field  : {
			email : 'E-mail'
		},
		label  : function() {
			if (!$(this).val()) {
				$(this).val(FORGOT.field[$(this).attr('name')]);
			}
		},
		clean  : function() {
			var name = $(this).attr('name');
			if ($(this).val() == FORGOT.field[name]) {
				$(this).val('');
			}
		},
		submit : function() {
			$('input', $(this)).each(FORGOT.clean);
		}
	};
	
	$('input', '.forgot').each (FORGOT.label);
	$('input', '.forgot').blur (FORGOT.label);
	$('input', '.forgot').focus(FORGOT.clean);
	
	$('.forgot').submit(FORGOT.submit);
	
	// profile
	var PROFILE = {
		field  : {
			email       : 'E-mail',
			last_name   : 'Фамилия',
			first_name  : 'Имя',
			middle_name : 'Отчество',
			birthday    : 'Дата рождения',
			inn         : 'ИНН',
			phone       : 'Телефон'
		},
		label  : function() {
			if (!$(this).val()) {
				$(this).val(PROFILE.field[$(this).attr('name')]);
			}
		},
		clean  : function() {
			var name = $(this).attr('name');
			if ($(this).val() == PROFILE.field[name]) {
				$(this).val('');
			}
		},
		submit : function() {
			$('input', $(this)).each(PROFILE.clean);
		}
	};
	
	$('input', '.profile').each (PROFILE.label);
	$('input', '.profile').blur (PROFILE.label);
	$('input', '.profile').focus(PROFILE.clean);
	
	$('.profile').submit(PROFILE.submit);
	
});

