$(function()
{
	update_login_status();
	
	var gap = $(window).height() - $(document.body).height();
	if (gap > 0) {
		$('#footer').height($('#footer').height()+gap);
	}
	
	$("ul.menu_umv > li > a").click(
			function() {
				var url = window.location.href;
				var host = "http://www.umiwi.com";
				if(url.indexOf(host) > -1) {
					click_track('navi',this.id, url.replace(host,''));
				}
			}
	);
	
	bind_float_menu();
	
	$('#searchform input.submit_search_header').click(
			function(){$('#searchform').submit()}
	);	
	$('#foot_feedback').click(function(){popup({title:'意见反馈',url:'/account/suggestion.php'});});
	
	updateHeaderPanels();
	
});


function updateHeaderPanels() {
	var hottags = $('#hottags').html();
	v = hottags == "{$g_hottags}" ? 1: 0;
	$.post('/ajax/header.php', {hottags:v}, function(data){
		if(window.location.href.indexOf('/search/result') < 0) {
			if(!data.defaultSearch) data.defaultSearch = "赢在中国";
			initSearchTips(data.defaultSearch);	
		}
		if(data.hottags) {

			$('#hottags').html(data.hottags);

		}
		if(data.my_reply_cnt > 0){ //2010-7-26
			//alert(data.my_reply_cnt);
			$('#my_reply_cnt_block').show();
			$('#my_reply_cnt').html(data.my_reply_cnt);
		}
//		if(data.ad) {
//			$('#headertopad').html(data.ad);
//		}
	},'json');
}

function initSearchTips(dv) {
	//search tips
	$("#searchform input.search_input_header").click(function(){
		sobj = $(this);
		if(sobj.val() == sobj.attr('defaultValue')) {
			sobj.val('');
			sobj.removeClass('gray');
		}
	}).blur(function(){
		sobj = $(this);
		if(sobj.val() == '') {
			sobj.addClass('gray');
			sobj.val(sobj.attr('defaultValue'));
		}
	}).attr('value',dv).attr('defaultValue',dv);
}

function bind_float_menu() {	
	//header sub menu init
	bind_float('auction',6);
	function bind_float(menu,x)
	{
		var timer;
		$('#navi_'+menu).mouseover(function(event)
		{
			try{ clearTimeout(timer); }catch(e) { }
			var offset = $(this).offset();
			$('#'+menu+'_menu_float').css({
				top:offset.top + $(this).height()+6,
				left:offset.left + x
			}).slideDown(200);
		}).mouseout(function()
		{
			timer = setTimeout(function()
			{
				$('#'+menu+'_menu_float').slideUp(200);
			},300);
		});
		$('#'+menu+'_menu_float').mouseover(function()
		{
			try{ clearTimeout(timer); }catch(e) { }
		}).mouseout(function()
		{
			timer = setTimeout(function()
			{
				$('#'+menu+'_menu_float').slideUp(200);
			},300);
		});
	}
}

if ($.msie) {
	try {
		document.execCommand("BackgroundImageCache",false,true);
	}catch(e){ }
}

function focus_navi(navi_id) {
	var obj = $('#navi_' + navi_id);
	obj.removeClass('top_nav_'+navi_id);	
	obj.addClass('navi_'+navi_id+'_on');
}

function getRadioCheckedValue(name) {
	var value = null;
	$("input[type=radio][name="+name+"]").each(
			function() {
				if(this.checked) {
					value = this.value;
					return true;
				}
			}
	);	
	return value;
}

function setRadioCheckedValue(name, value) {
	$("input[type=radio][name="+name+"]").each(
			function() {
				if( this.value == value) {
					this.checked = true;
					return;
				}
			}
	);
}

function isUserLogined() {
	var username = $.cookie('username');
	if(username == null || $.trim(username) == '') {
		return false;
	}
	return true;
}

function login(callback)
{	if(typeof(callback) =="function")
	    window.login_success_callback = callback;
	popup({url:'/account/login.php?from=ajax',title:"登录"});
}

function logout()
{
	$.post('/account/login.php?action=logout&t='+Math.random(),{ },function(s)
	{
		update_login_status();
	});
}

function register()
{
	popup({url:'/account/register.php',title:'注册'});
}

function update_login_status()
{
	if (isUserLogined())
	{
		$('#head_login').hide();
		$('#head_loggedin').show().find('tt').html($.cookie('username'));
	}
	else
	{
		$('#head_loggedin').hide();
		$('#head_login').show();
	}
}

function popup(data)
{
	hide_selects();
	$('.popup_error').remove();
	data.width = 555;
	if (!data.height) data.height = 100;
	if (window.popup_last_height) data.height = window.popup_last_height;
	if (!data.title) data.title = 'UMIWI';
	var body = document.documentElement || document.body;
	//获得页面尺寸信息
	var page = get_page_size();
	//如果没有黑色背景
	if ($('#popup_bg').length == 0)
	{
		$('<div id="popup_bg"></div>').css(
		{
			height: page.height,
			width: $(window).width(),
			zIndex: '99999',
			position:'absolute',
			top:0,
			left:0,
			padding:0,
			backgroundColor:'#000000',
			margin:'0px'
		})
		.css('opacity',0)
		.attr('popup','yes')
		.bind('click',close_popup)
		.appendTo(document.body)
		.fadeTo(300,0.7);
	}
	
	//计算窗口位置
	data.top = page.scrollTop + ($(window).height() - data.height ) / 2 - 50;
	data.left =  ($(window).width() - data.width ) / 2;

	//删除上次弹出的窗口
	$('#popup').remove();
	
	//创建新的弹出窗口
	var div = document.createElement('div');
	$(div)
		.css(
		{
			width: data.width,
			zIndex: 100000,
			backgroundColor: 'transparent',
			position:'absolute',
			padding:'0px',
			margin:'0px',
			opacity:0.98,
			overflow:'auto',
			top:data.top,
			left:data.left
		})
		.attr('popup','yes');
	
	$(div)
		.attr('id','popup')
		.html('<div id="popup_top_wrapper"><div class="popup_top_bar"><img src="/images/blank.gif"/></div>'
			+'<div class="popup_top" id="popup_top">'
	    	+'<span class="popup_title"><strong class="orange" id="popup_title">'+data.title+'</strong></span>'
	        +'<a class="popup_close_button" href="javascript:close_popup();"></a>'
	    	+'</div></div><div class="popup_content">'
	    	+'<div class="popup_main">'
			+'<div id="popup_content" style="overflow:auto;height:'+parseInt(data.height)+'px;'
			+'background:transparent url(/images/loading.gif) no-repeat 50% 50%;">'
	        +'<div id="popup_content_inner"></div></div></div>  </div>'
			+'<div class="popup_bottom"><img src="/images/blank.gif"/></div>')
		.attr('source_src',data.url);
		
	$(document.body).append(div);
	
	show_msg = function(s)
	{
		//动态适应高度
		var size_to_height = function()
		{
			var page = get_page_size();
			$('#popup_content_inner').css('height','10').html(s);
			setTimeout(function()
			{
				var height = $('#popup_content_inner').get(0).scrollHeight+2;
				//document.title = window.popup_last_height + ' '+ height;
				window.popup_last_height = height;
				$('#popup_content_inner').height(height);

				$('#popup_content')
					.css('background','#ffffff none no-repeat -1000px 0px');

				var top = page.scrollTop + ($(window).height() - height ) / 2 - 50;
				
				$('#popup').animate({top:top},300);
				$('#popup_content').css('overflow','hidden').animate(
					{
						opacity:1,
						height:height
					},300);
			},0);
			
		}
		
		//如果IE6 或者 IE7 关闭动画效果，直接显示
		if ($.browser.msie && ($.browser.version == 6 || $.browser.version == 7))
		{
			size_to_height();
		}
		else
		{
			$('#popup_content').fadeTo(300,0,size_to_height);
		}
		
	};
	if (data.url)
		$.get(data.url,{ },show_msg);
	else if (data.content)
		show_msg(data.content);
}

function show_popup_loading()
{
	$('#popup_content').css('background','#fff url(/images/loading.gif) no-repeat 50% 50%');
	$('#popup_content_inner').hide();
	$('.popup_error').hide();
}

function hide_popup_loading()
{
	$('#popup_content').css('background','#fff none no-repeat 50% 50%');
	$('#popup_content_inner').show();
	$('.popup_error').show();
}

function popup_resize(callback)
{
	var page = get_page_size();
	var height = $('#popup_content_inner').get(0).scrollHeight+2;
	if (height != window.popup_last_height)
	{
		window.popup_last_height = height;
		$('#popup_content_inner').height(height);
		var top = page.scrollTop + ($(window).height() - height ) / 2 - 50;
	
		$('#popup').animate({top:top},300);
		$('#popup_content').css('overflow','hidden').animate(
			{
				opacity:1,
				height:height
			},300,callback);
	}
	else callback();
}

function get_page_size()
{
	var re = {};
	if (document.documentElement && document.documentElement.clientHeight)
	{
		var doc = document.documentElement;
		re.width = (doc.clientWidth>doc.scrollWidth)?doc.clientWidth:doc.scrollWidth;
		re.height = (doc.clientHeight>doc.scrollHeight)?doc.clientHeight:doc.scrollHeight;
		re.scrollTop = (doc.scrollTop>document.body.scrollTop)?doc.scrollTop:document.body.scrollTop;
		re.scrollHeight = (doc.scrollHeight>document.body.scrollHeight)?doc.scrollHeight:document.body.scrollHeight;
	}
	else
	{
		var doc = document.body;
		re.width = (window.innerWidth>doc.scrollWidth)?window.innerWidth:doc.scrollWidth;
		re.height = (window.innerHeight>doc.scrollHeight)?window.innerHeight:doc.scrollHeight;
		re.scrollTop = doc.scrollTop;
		re.scrollHeight = doc.scrollHeight;
	}
	return re;
}


function close_popup()
{
	show_selects();
	window.popup_last_height = $('#popup_content').height();
	$('[popup]').fadeOut('fast',function()
	{
		$('[popup]').remove();
		$('.popup_error').remove();
	});
	
}

function hide_selects()
{
	$('select').hide();
}

function show_selects()
{
	$('select').show();
}

function show_error(content,o,id)
{
	var animation = 300;
	id += 'error_box';
	if ($('#'+id).length > 0) animation = 0;
	$('#'+id).remove();
	o = $(o);
	//偏移分量
	x = parseInt(o.attr('offsetx'));
	if (!x || isNaN(x)) x = 20;
	var html = '<div class="errtip_periphery">'
    	+'<div class="errtip_side_top"><img src="/images/error_top.gif"/></div>'
        +'<div class="error_main">'
        	+'<div class="error , red">'
			+content
          +'  </div>'
        +'</div>'
        +'<div class="errtip_side_bottom"><img src="/images/error_bottom.gif"/></div>'
    +'</div>';
	$('<div class="popup_error" id="'+id+'"></div>').html(html).appendTo(document.body).css({
		top:parseInt(o.offset().top)-8,
		left:parseInt(o.offset().left) + parseInt(o.width()) + x,
		zIndex:100001
	}).fadeIn(animation);
}

function hide_error(o,id)
{
	id += 'error_box';
	$('#'+id).remove();
	o = $(o);
	var html = '<img class="correct_img" src="/images/right_pic.gif" />';
	$('<div class="popup_error" id="'+id+'"></div>').html(html).appendTo(document.body).css({
		top:parseInt(o.offset().top)-8,
		left:parseInt(o.offset().left) + parseInt(o.width()) + 20,
		zIndex:100001
	}).fadeIn(300);
}


function flash(data) 
{
	if (!data.id) data.id = 'flash_'+parseInt(Math.random()*10000);
	if (!data.vars) data.vars = '';
	if (!data.bgcolor) data.bgcolor = '#000000';
	if (!data.width) data.width = '';
	if (!data.height) data.height = '';
	if (!data.src)
	{
		alert('writeflashobject error! need src');
		return;
	}
	if (!data.wmode) data.wmode = 'Opaque';
	var str ='';
	str += ("<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\""+data.width+"\" height=\""+data.height+"\" id=\""+data.id+"\" align=\"middle\"\>\n");
	str += ("<param name=\"allowScriptAccess\" value=\"sameDomain\" /\>\n");
	str += ("<param name=\"movie\" value=\""+data.src+"\" /\>\n");
	str += ("<param name=\"FlashVars\" value=\""+ data.vars +"\" /\>\n");
	str += ("<param name=\"quality\" value=\"high\" /\>\n");
	str += ("<param name=\"wmode\" value=\""+data.wmode+"\" /\>\n");
	str += ("<param name=\"bgcolor\" value=\""+data.bgcolor+"\" /\>\n");
    str += ("<param name=\"allowFullScreen\" value=\"true\" /\>\n");
	str += ("<embed src=\""+data.src+"\" quality=\"high\" wmode=\""+data.wmode+"\" bgcolor=\""+data.bgcolor+"\" width=\""+data.width+"\" height=\""+data.height+"\" name=\""+data.id+"\" allowFullScreen=\"true\" align=\"middle\" allowScriptAccess=\"sameDomain\"  allowScriptAccess=\"sameDomain\" FlashVars=\""+ data.vars +"\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" /\>");
	str += ("</object\>");
	if(!data.container) {
		document.write(str);
	} else {
		$(data.container).html(str);
	}
}

jQuery.fn.makePager = function(settings)
{
	settings = jQuery.extend(
	{
		url: window.location.href.toString(),
		total:1,
		current:1,
		container:'',
		onPage:null
	},settings);
	
	var createLink = function(page)
	{
		return "<a align='absmiddle' class='num_out' href='"+settings.url+settings.mark+"page="+page+"' onmouseover=\"className='num_over'\" onmouseout=\"className='num_out'\">"+page+"</a>";
	};
	var filtervar = function(url) {
		return url.replace(/page=\d+/g,"");		
	};
	var getCurrentPage = function(url) {
		var r = /page=(\d+)/g;
		if(r.test(url)) {
			return RegExp.$1;
		}
		return 1;
	};
	
	var self = $(this);
	settings.current = getCurrentPage(settings.url);
	settings.url = filtervar(settings.url);
	settings.mark = (settings.url.indexOf('?') == -1)?'?':'&';
	
	buildPager = function(page)
	{
		self.html('');
		var pager = '';
		var total = settings.total;
		if (total <= 1) return;
		if (!page) page = 1;
		var page_span = 3;
		
		if (page > 1) //previous page
		{
			$('<a href="'+settings.url+settings.mark+'page='+parseInt(page-1)+'" class="pager">'
			+'<img width="54" height="21" align="absmiddle" onmouseover="src=\'/images/subpage_move_up.gif\'"  onmouseout="src=\'/images/subpage_out_up.gif\'" src="/images/subpage_out_up.gif" />'
			+'</a>')
				.click(function(event)
				{
					event.preventDefault();
					goto_p(page-1);
					return false;
				}).appendTo(self);
		}

		if (page - page_span >= 2)
		{
			$(createLink(1)).click(function(event)
			{
				event.preventDefault();
				goto_p(1);
				return false;
			}).appendTo(self);
		}
		if (page - page_span > 2)
		{
			$('<span>...</span>').appendTo(self);
		}
		
		for(i=page-page_span;i<=page+page_span;i++)
		{
			if (i<=0 || i>total) continue;
			if (page == i)
				$('<span class="num_over">'+i+'</span>').appendTo(self);
			else
				$(createLink(i)).data('page',i).click(function(event)
				{
					event.preventDefault();
					goto_p($(this).data('page'));
					return false;
				}).appendTo(self);
		}
		if (total- page - page_span > 1)
		{
			$('<span>...</span>').appendTo(self);
		}
		if (total- page - page_span >= 1)
		{
			$(createLink(total)).click(function(event)
			{
				event.preventDefault();
				goto_p(total);
				return false;
			}).appendTo(self);
		}
		if (page < total)
		{
			$('<a href="'+settings.url+settings.mark+'page='+(page+1)+'" class="pager">'
			+'<img width="54" height="21" align="absmiddle" onmouseover="src=\'/images/subpage_move_next.gif\'"  onmouseout="src=\'/images/subpage_out_next.gif\'" src="/images/subpage_out_next.gif" />'
			+'</a>')
				.click(function(event)
				{
					event.preventDefault();
					goto_p(page+1);
					return false;
				}).appendTo(self);
		}
		return pager;
	}
	
	var goto_p = function(page,forceload)
	{
		if (page<=0) page = 1;
		var total_page = settings.total;
		if (page > total_page) page = total_page;
		if (page == settings.current && !forceload) return;
		var url = settings.url+settings.mark+'page='+page+'&ajax=true';
		var loading = true;
		$(settings.container).after('<div class="pager-loading"></div>');
		$(settings.container).slideUp(300,function() //评论内容收上去之后执行这个函数
		{
			// 翻页问题
			var bd = (document.documentElement && document.documentElement.scrollTop>0)?document.documentElement:document.body; //得到页面元素
			bd.scrollTop = $(settings.container).offset().top;
		});
		
		$.post(url,{  },function(s)
		{
			loading = false;
			settings.current = page;
			$('.pager-loading').slideUp(200,function() //删除loading的那个图片
			{
				$(this).remove();
			})
			$(settings.container).html(s+'<div class="clear"></div>').slideDown(300,function()
			{
				if (settings.onPage && typeof settings.onPage == 'function') settings.onPage.call(this);
			});
			buildPager(page);

			//lll 2010-5-26 翻页时也自动展开回复内容
			if(typeof(commont_reply_start_DirectDisplay)=="function"){
				commont_reply_start_DirectDisplay();
			}
		});
	}
	
	buildPager(settings.current);
	return self;
};

function click_track(cate, action, label, value) {
	try{
	if(pageTracker) {
		pageTracker._trackEvent(cate, action, label, value);
	}} catch(ex){}
}

function update_visit_num(type, id) {
	$(function(){$.post('/ajax/update_visit.php?t='+Math.random(),{type:type,id:id},function(data){
	    $('#visit_num').html(data);
	});});
}

function not_empty(data) {
    if(data !=null && typeof(data) !='undefined' && $.trim(data) != '') {
	return true;
    }
    return false;
}