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() {
		$('#mlogin').load('/status_box/', '', function(data){
			$(this).html(data);
		});
		$('#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;
//			}
//		});  
        $('#bbsdraw').hoverAccordion();
		$($('#bbsdraw a.img_link')[0]).removeClass('closed').addClass('opened');
		$($('#bbsdraw ul')[0]).show();
		
		$('#recommend_recipe_slider .tabs').idTabs({
			event: '!mouseover',
			display: 'fadeIn'
		});
		
		
		$('#t_sina').idTabs({
			event: '!mouseover',	
			display: 'fadeIn'	
		});
		
		$('#top_recipes').idTabs({
			event: '!mouseover',
			display: 'fadeIn'
		});
		$('#top_videos').idTabs({
			event: '!mouseover',
			display: 'fadeIn'
		});
		
		$('#top_videos a[href=#tl_official]').hover(function(){
			$('#tl_official iframe').each(
				function(){
				$(this).attr('src',$(this).attr('src'))
			})
		});
		
		$('#top_videos a[href=#tl_recommend]').hover(function(){
			$('#tl_recommend iframe').each(
				function(){
				$(this).attr('src',$(this).attr('src'))
			})
		});
	},
	vote: function() {
		var flag_type = {
			bought: 1,
			want: 2,
			favorite: 3
		};
		var msgs = {
			ajax_err: '出错了……请刷新页面后重新尝试一下',
			signin_signup: '<div>感谢您的关注，您需要 <a href="/signin/?next='+escape(document.location.pathname)+'">注册或登录</a> ',
			comment_not_empty: '请先填写评价的内容'
		};
		var popup = function(msg) {
			if (typeof $.colorbox === 'undefined') {
				alert($('<div>').html(msg).text());
			}
			else {
				$.colorbox({html:msg, close:'<a href="javascript:void(0);">关闭</div>'});
			}
		};

		return {
			init: function(pid, logged_in) {
				if (!logged_in) {
					var msg = msgs.signin_signup;
					$('#vote a').click(function(){
						popup(msg + '来作评价');
						return false;
					});
					$('div.comment_box a.agree').live('click', function(){
						popup(msg + '以支持这条评价');
						return false;
					});
					$('#add_comment a').click(function(){
						popup(msg + '来评价商品');
						return false;
					});
				}
				else {
					$('#a_comment_up, #a_comment_down').click(function() {
						var $this = $(this);
						// check data
						if ($.trim($('textarea[name=comment]').val()).length == 0) {
							popup(msgs.comment_not_empty);
							return false;
						}
						$('#add_comment input[name=is_up]').val($this.attr('id')=='a_comment_up'?'True':'');
						$.ajax({
							type: 'POST',
							url: '/marketplace/product/'+pid+'/add-comment/',
							data: $('#add_comment').serialize(),
							dataType: 'json',
							success: function(data) {
								if (data.success) {
									// update comment
									if (data.refresh) {
										var comments = '#'+$this.attr('id').slice(2);
										// update count, possibly switch tab
										var tab_link = $('#comment_tabs a.box[href='+comments+']:eq(0)')
										tab_link.click();
										var comment_count = parseInt(tab_link.html().match(/\d+/)[0]) + 1;
										tab_link.html(tab_link.html().replace(/\d+/, comment_count));
										var bg_color = (comments == '#comment_up')?'lightyellow':'lightgreen';
										$(data.msg).appendTo(comments).find('div.comment_detail').css('background-color', bg_color).animate({'background-color':'#f0f0f0'}, 1000);
									}
									else {
										popup(data.msg);
									}
									$('#add_comment textarea').val('');
								}
								else {
									popup(data.msg);
								}
							},
							error: function(xhr, e) {
								popup(msgs.ajax_err);
								$this.removeClass('disabled');
							}
						});
					}); // $('#a_comment_up, #a_comment_down').click
					$('#vote a').click(function(){
						var $this = $(this);
						var id = $this.attr('id');
						if (!$this.hasClass('flagged') && !$this.hasClass('disabled') && id in flag_type) {
							$this.addClass('disabled');
							$.ajax({
								type: 'POST',
								url: '/marketplace/product/'+pid+'/flag/',
								data: {
									// check
									flag: flag_type[$this.attr('id')]
								},
								dataType: 'json',
								success: function(data) {
									if (data.success) {
										$this.siblings('#'+id+'_count').text(data.msg).end().addClass('flagged');
									}
									// popup(data.msg);
									$this.removeClass('disabled');
								},
								error: function(xhr, e) {
									popup(msgs.ajax_err);
									$this.removeClass('disabled');
								}
							});
						};
						return false;
					}); // $('#vote a').click
					$('div.comment_box a.agree').live('click', function(){
						var $this = $(this);
						if (!$this.hasClass('disabled')) {
							$this.addClass('disabled');
							$.ajax({
								type: 'POST',
								url: '/marketplace/comment/'+$('input', $this).val()+'/up/',
								data: {},
								dataType: 'json',
								success: function(data) {
									if (data.success) {
										$this.replaceWith(data.msg);
										// not update score currently
									}
								},
								error: function(xhr, e) {
										popup(msgs.ajax_err);
										$this.removeClass('disabled');
								}
							}); // $.ajax
						}
						return false;
					}); // $('div.comment_box a.agree').live
				}
			} // big init
		};
	}(),
	mp: {
    init_top_with_image: function(selector) {
		  $(selector).hover(
        function(){
          var $this = $(this);
          $this.addClass('over');
          var span_box = $this.find('span.box');
          if ($('img', span_box).length===0) {
            var img = $('<img/>');
            img.attr({src:$this.find('a.img_link').attr('href'),width:60,height:60});
            span_box.append(img);
          }
          span_box.find('img').show();
          $this.siblings().removeClass('over').find('img').hide();
        },
        function(){}
      ).filter('.row1').hover();
    },
    init_weekly_bestseller: function() {
      BK.mp.init_top_with_image('#weekly_bestseller li');
    },
		init_remove_recently_visited: function() {
			$('#remove_recently_visited').click(function(){
				var $this = $(this);
				$.ajax({
					type: 'post',
					url: '/marketplace/product/remove-recently-visited/',
					data: {},
					dataType: 'json',
					error: function(xhr, e) {
					},
					success: function(data, tx, xhr) {
						$this.parent().next().find('table').remove();
					}
				});
				return false;
			});
		}
	}
}
var popup = function(msg) {
  $.colorbox({html:msg, close:'<div><a href="javascript:;">关闭</a></div>'});
};
$(function() {
	BK.search_box_init();
	BK.hover_class($('#old_nav li'), 'sfhover');
	BK.slider_box_init();
	BK.video_box_init();
	BK.mlogin_load();
});

