var BK = {
	sfilter_init: function(base_path){
		var sf = $('#sfilter');
		var sf_link = $('#sfilter_submit');
		BK.hover_class(sf.find('li.item'), 'over');
		var ptn = new RegExp('/?' + base_path.slice(1) + '(([^/]*)/?)?');
		sf.click(function(e){
			if (e.target.nodeName.toLowerCase() === 'a') {
				var t = $(e.target);
				t.addClass('selected').siblings().removeClass('selected');
				t.parents('li.item').find('span.selected_opt').text(t.text());
				// update link
				var tmp = [];
				sf.find('a.selected').each(function() {
					tmp.push(this.pathname.replace(ptn, '$2'));
				});
				var r = tmp.join('');
				sf_link.attr('href', base_path+(r?r+'/':''));
				return false;
			}
		});
	},
	recipe_index_init: function() {
		$('.green_box .idTabs_g').idTabs({event:'!mouseover', display:'fadeIn'});
		$('#recommend_recipe_slider .tabs').idTabs({event: '!mouseover', display: 'fadeIn'});
		BK.sfilter_init('/search/recipe/');
	},
	check_empty: function(t) {
		if (t != null && !t.value){
			alert("回复内容不能为空");
			t.focus();
			return false;
		}
		return true;
	},
	search_box_init: function() {
		var $search_q = $('#search_q');
		var default_search_keywords = {'#search_bbs':'搜索您感兴趣的论坛帖子', '#search_site':'搜索您感兴趣的分类菜谱', '#search_video':'搜索您感兴趣的视频'};
		var default_actions = {'#search_site':'/search/recipe/','#search_bbs':'/bbs/search.php?mode=results','#search_video':'/video/search/'};
		$("#search_type").idTabs(function(id){ 
			var action = default_actions[id];
			var form_method = 'get';
			var name = 'q';
			if (id == '#search_bbs') {
				name = 'search_keywords';
				form_method = 'post';
				$search_q.after($('<span id="search_extra_input"><input type="hidden" name="search_terms" value="any" /><input type="hidden" name="show_results" value="topics" /></span>'));
			}
			else {
				$('#search_extra_input').remove();
			}
			$search_q.attr('name', name);
			$("#search_form").attr({'action':action, 'method':form_method});
			if (!$search_q.hasClass('q_modified')) {
				$search_q.val(default_search_keywords[id]);
			}
			return true; 
		}); 
		$search_q.focus(function(){ 
			var $this = $(this);
			if (!$this.hasClass('q_modified')) { $this.val('').addClass('q_modified'); }
		});
		$search_q.blur(function(){ 
			var $this = $(this);
			if ($this.val() == '') {
				$this.removeClass('q_modified');
				$this.val(default_search_keywords[$('#search_type .selected').attr('href')]);
			}
		});
	},
	hover_class: function(objs, cls) {
		// objs = $(objs);
		objs.hover(
			function(){$(this).addClass(cls);},
			function(){$(this).removeClass(cls);}
		);
	},
	mlogin_load: function() {
		submit_func = function(){
			$(':submit', this).attr('disabled', 'disabled');
			$.post('/signin-box/', $(this).serialize(), function(data){
				if ($(data).find('a').hasClass('logged')) {
					location.reload();
				}
				else {
					$('#mlogin').html(data).find('form').submit(submit_func);
				}
			});
			return false;
		};
		$('#mlogin').load('/signin-box/', '', function(data){
			$(this).find('form').submit(submit_func);
		});
		$('#status_box').load('/people/status-box/', '', function(){
			$('#status_box').idTabs({event:'!mouseover', display:'fadeIn'});
			$('#s_subscribe [name=email]').val('请输入您的电子邮件').css('color', '#999').focus(function(){ $(this).val('').css('color', '#333'); });
			$('#s_subscribe form').submit(function(){
				var submit_btn = $(':submit', this);
				submit_btn.attr('disabled', 'disabled');
				$.post(this.action, $(this).serialize(), function(data){
					if (data.match(/^OK/)) { alert('您已成功订阅，感谢您对贝太的关注。'); }
					else { alert('邮件地址的格式不正确，请重试...'); }
					submit_btn.removeAttr('disabled');
				});
				return false;
			});
		});
	},
	slider_box_init: function() {
		var i = 1;
		// Initial all of the sliders in the page.
		$('div.slider_detail').each(function(){
			$(this).easySlider({
				prevId: 'prevBtn'+i,
				nextId: 'nextBtn'+i,
				speed: 500
			});
			i++;
		});
	},
	video_box_init: function() {
		// Modify the video link, display the video in a big overlay box.
		// Format: <a href="[video_url]" class="video_link img_link"><img src="[video_img_url]" /></a>
		var video_uuid = 0;
		$('a.video_link').each(function(){
			var $this=$(this), v_url=$this.attr('href'),
					$v_img = $('img', $this),
					$hide = $('<div class="hide"></div>'),
					vid= 'video_'+(++video_uuid),
					$v = $('<div id="'+vid+'"></div>');
			$this.replaceWith($v_img);
			$hide.append($v);
			$v_img.after($hide);
			swfobject.embedSWF(v_url, vid, "608", "480", "9", "", {}, {wmode:'opaque'});
			$v_img.colorbox({inline:true, width:660,height:560,
				close:'关闭', href:'#'+vid},
				function(){
					// workaround: The video object can't display after first time in IE.
					// It seems a bug of IE browser, including IE8.
					// Set opacity value to 1 directly doesn't work.
					$('#colorbox').fadeTo(0, 1);
				});
			// Add hand cursor for the image.
			$v_img.css('cursor', 'pointer');
		})
	},
	competition_base_init: function() {
		// Initial competition navigation bar
		$('#comp_navigation').idTabs(function(id){
			$('#center_content').hide();
			$('#comp_navigation a').addClass('nobg');
			return true;
			},
			{start: null}
    );
	},
	site_index_init: function() {
		var is_user_click = false;
		var interval_id = null;
		show_next_news = function () {
			// This type of function definition raise an exception in IE.
			// function show_next_news() {
			var a_list = $('.promote_control a');
			var cur = a_list.filter('.selected')[0];
			var next_index = a_list.index(cur) + 1;
			var next = a_list.length > next_index ? a_list[next_index] : a_list[0];
			if (is_user_click) {
				// stop loop if the user choose one.
				if (interval_id) { clearInterval(interval_id); }
				return 0;
			} else {
				try {
					// Hide the original selected tab, active the next one.
					if (cur) {
						var id = "#" + $(cur).attr('href').split('#')[1];
						$(cur).removeClass('selected');
						$(id).hide();
					}
					if (next) {
						id = "#" + $(next).attr('href').split('#')[1];
						$(next).addClass('selected');
						$(id).show();
					}
				} catch (e) { return 0; }
				return 1;
			}
		}
		$('#news_promote .promote_control').idTabs({
			click: function(){ is_user_click=true; return true; },
			start: null,
			event: '!mouseover',
			display: 'fadeIn'
		});
		interval_id = setInterval('show_next_news()', 5000);
		show_next_news();
		$('#bbs .col_thread').idTabs({
			event: '!mouseover', 
			display: 'fadeIn',
			click: function(id) {
				$('#bbs .col_thread li').removeClass('selected');
				$(this).parent().addClass('selected');
				return true;
			}
		});
		$('#recommend_recipe_slider .tabs').idTabs({
			event: '!mouseover',
			display: 'fadeIn'
		});
		$('#top_recipes').idTabs({
			event: '!mouseover',
			display: 'fadeIn'
		});
		$('#top_videos').idTabs({
			event: '!mouseover',
			display: 'fadeIn'
		});
	}
}

$(function() {
	BK.search_box_init();
	BK.hover_class($('#nav li'), 'sfhover');
	BK.slider_box_init();
	BK.video_box_init();
	BK.mlogin_load();
});
