$(function(){
	var title_bg_class ='.sh_title';
	var logos_ul_position = $('#id_sh_title_logos').offset();
	if(!$.support.tbody){
		title_bg_class ='.sh_title_bgcolor'; 
		$(".sh_title").wrap('<span class="sh_title_bgcolor"></span>');
	}
	var img_mesh = new Image();
	img_mesh.src = '/sites/all/themes/shufu/img/sh_mesh.png';
	var logo_colors = ['#EB0533','#007D00','#003973','#F2C50D','#D84174'];
	var cover_cache = [];
	$("a.sh_title").each(function(){
		var img_src = '';
		if($(this).attr('cover_img') != undefined && $(this).attr('cover_img') != ''){
			img_src = $(this).attr('cover_img');
			var img_tmp = new Image();
			img_tmp.src = img_src;
			cover_cache.push(img_tmp);
			
		}
		if($.support.tbody){
			$(this).data('cover_url',img_src);
		}else{
			$(this).closest('span').data('cover_url',img_src);
		}
	});
	$(title_bg_class).each(function(){
		var li_position = $(this).closest('li').offset();
		var left_offset = li_position.left - logos_ul_position.left;
		if($.support.cssFloat){
			var top_offset = li_position.top - logos_ul_position.top;
		}else{
			var top_offset = li_position.top - $("#id_sh_title_logos li:first").offset().top;
		}
		$(this).data('logo_data',{'index':$(title_bg_class).index(this),'top_offset':top_offset,'left_offset':left_offset});
		var html = '<div class="sh_title_mesh" style="position:absolute; top:5px; left:5px; background-repeat: no-repeat;background-position:-'+ left_offset+ 'px -'+ top_offset+ 'px;display:none;"><img src="'+ img_mesh.src + '" /></div>';
		$(this).before(html);
	})
	
	var logo_num = $(".sh_title").length;
	
	function colorchange(obj,type){
		if(type=='start'){
			var color_pick = Math.floor( Math.random() * (logo_colors.length) );
			obj.colortimer = setTimeout(
				function(){
					$(obj).animate({backgroundColor: logo_colors[color_pick] }, 4000,
									function(){colorchange(obj,'finish');}
					);
				},
				Math.floor( Math.random() * 10)*1000
			);
		}else{
			$(obj).animate({ backgroundColor: '#111'}, 3000, function(){colorchange(obj,'start')});
		}
	}
	
	$(title_bg_class).bind('colorchange',{},function(){$(this).css('background-color','#111');colorchange(this,'start')});
	$(title_bg_class).bind('colorchange_stop',{},
						function(e,target){
							clearTimeout(this.colortimer);
						});
	$(title_bg_class).trigger('colorchange');
	$(title_bg_class).mouseover(function(){
		if($(this).data('cover_url') != ""){
			$(title_bg_class).stop();
			$(title_bg_class).trigger('colorchange_stop',[this]);
			$(title_bg_class).not($(this)).css('background-color','#111').hide();
			$(this).css('background-color','#EB0533');
			$(".sh_title_mesh").css('background-image','url(' + $(this).data('cover_url') + ')');
			$(".sh_title_mesh").not($(this).prev()).fadeIn('fast');
			
			
			
		}
	});
	$(title_bg_class).mouseout(function(){
		$(".sh_title_mesh").fadeOut(600);
		$(title_bg_class).show().trigger('colorchange');
	});
});
