// JavaScript Document
$(function(){
		   //$("#sidebar").height().change(function(){
		var leftHeight = $("#sidebar").height(); 
		var rightHeight = $("#main").height();
		
		if (leftHeight < rightHeight) {
			$("#sidebar").height(rightHeight);
		}else{
			$("#main").height(leftHeight);
		}
	//})
})

//用户状态选择
$(function(){
	   $("#userState li:has(ul)").hover(function(){
			$(this).children("ul").stop(true,true).slideDown(600);
        },function(){
		    $(this).children("ul").stop(true,true).slideUp("fast");
		});
	   
	   $("#userState li ul li a").click(function(){
			var data1 = $(this).html(); //取得单击的这个a的值
			$(this).parent().hide(); //把父级标签li隐藏
			var $parent = $(this).parent(); 
			$parent.siblings("li").show(); //把父级标签li的其他兄弟标签显示
			$('.selState a:first').html(data1);
        });
});

//模块的打开和关闭
$(function(){
		 $(".moduleUpDown").toggle(function(){
					var $self = $(this);
					$("#myTree").slideToggle(600,function(){
						  $self.attr("class","isOpen");
					});
			 },function(){
					var $self = $(this);
					$("#myTree").slideToggle(600,function(){
						  $self.attr("class","isClose");
					});
		 })
})


/*产品树展开和关闭*/
$(function(){
	   $("#myTree > li > a").click(function(){
			    var $ul = $(this).siblings("ul");
				if($ul.is(":hidden")){
					$ul.slideDown(400);
					$(this).parent().attr("class","m-expanded");
				}else{

					$ul.slideUp(400);
					$(this).parent().attr("class","m-collapsed");
				}
	   })
})

/*图片导航和文字导航的切换*/
$(function(){
		 $(".picMenu").click(function(){
					var $op = $("#nav .navPic");
					if($("#nav").is(":hidden")) {
						$("#nav").slideDown(400);
					}
					$op.slideDown(400);
					return false;
		 });
		 $(".textMenu").click(function(){
					var $op = $("#nav .navPic");
					if($("#nav").is(":hidden")) {
						$("#nav").slideDown(400);
					}
					$op.slideUp(400);
					return false;
		 });
		 $(".closeMenu").click(function(){
					$("#nav").slideUp(400);
					return false;
		 })
})

/*  改变文本框 */
function change(id) {
	var idName = "#"+id;
	$("#tabInput .inputBox:visible").slideUp(400)
						  .addClass('hide');
	$(idName).slideDown(400);
}

/* 关闭朋友信息 */
$(function(){
	$(".closeFriInfo").click(function(){
		var $op = $(this).parent().parent();
		$op.slideUp(400);
		//alert($(this).attr("href"));
		$.ajax({'url' : $(this).attr("href"),'type' : 'get'});
		return false;
	});
})

/* 选项卡 */
$(function(){
	    var $op =$("#tabMenu > ul > li > a");
	    $op.click(function(){
			var $par = $(this).parent(); //取得自己的父元素
            var index =  $op.parent().index($par); // 获取自己的父元素 在 全部li元素中的索引。
			$(this).addClass("selected");           //当前<a>元素高亮
			$(this).parent().siblings().children("a").removeClass("selected"); //去掉他父亲<li>元素的其它同辈<li>元素下<a>的高亮
			
			var idName = "#subMenu"+index;
			
			if ($(idName).length > 0) {
				$(idName).attr("class",'');
				$(idName).siblings().attr("class",'hide');
				
				var firstChild = idName+" li:first";
				var firstChildStr = idName+" li:first a";
				if($(firstChildStr).length > 0) {
					$(firstChildStr).click();
				}else{
					$("#subTabMenu").find("ul").attr("class",'hide');
					$("#tabInput .inputBox").attr("class",'hide');
				}
				
			} else {
				
				$("#subTabMenu").find("ul").attr("class",'hide');
				
			}
			
			
			$("#tabBox > div")   	//选取子节点。不选取子节点的话，会引起错误。如果里面还有div 
					.eq(index).show()   //显示 <li>元素对应的<div>元素
					.siblings().hide(); //隐藏其它几个同辈的<div>元素
					
		})
	})

$(function(){
	$(".ajaxbox").colorbox();
	$(".boxdel").colorbox({
		width:"50%", 
		inline:true, 
		href:"#confirmdiv",
		onOpen:function(){$("#confirm").attr("action",$(this).attr('href')); }
	});
})

function parseJSON(data){
	if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
	  return { status: 0, data: data.length ? data : 'Unspecified error' };
	}
	  return eval('(' + data + ');');
}

/*
 * @autocomplete 
 */
$.fn.autocomplete = function(options){
	var defaults={
		url: 'index.php?s=/ajax/autocomplete',
		chars: 1,
		width: 300,
		height: 150,
		top: null,
		left: null,
		time: 400,
		sroll: false
	};
	var ops = $.extend(defaults,options);
	var pop = $('<div id="autocomplete"></div>');
	var results = $('<ul id="results"></ul>');
	var doneUsers = {};
	var curPos;
	if(ops.top != null){pop.css('top',ops.top);}
	if(ops.left != null){pop.css('left',ops.left)}
	$(this).after(pop).parent().css('position','relative');
	pop.css({'width':ops.width+'px'}).hide().append(results);
	if(ops.sroll){
		pop.css({'height':ops.height+'px','overflow':'auto'});
	}
	function quest(q,elem){
		var w = $.trim(q.substr(q.lastIndexOf(',')+1,q.length));
		if(w.length >= ops.chars){
			curPos = null;
			$.ajax({
				type: 'GET',
				url: ops.url+'/prefix/'+w,
				cache: false,
				success: function(data){
					jdata = parseJSON(data);
					if(jdata.length > 0){
						loadDone(elem);
						var str = '';
						if(jdata.length > 10){
							results.css({overflow:'auto',height:'240px'});
						}else{
							results.css({overflow:'hidden',height:'auto'});
						}
						for(var j = 0; j < jdata.length;j++){
							if(! doneUsers[jdata[j]]){
								str += '<li>'+jdata[j]+'</li>';
							}
						}
						results.html(str);
						updataePos(results.children('li').eq(0))
						results.children('li').mouseover(function(){
							updataePos($(this));
						}).click(function(){
							addValue($(this).text(),elem);
						})
						if(results.children('li').size() > 0){
							pop.show();
						}else{
							pop.hide();
						}
					}else{
						pop.hide();
					}
				}
			});	
		}
	}
	$(document).click(function(){
		pop.hide();
	});
	pop.click(function(){stopBubble();});
	function loadDone(elem){
		doneUsers = {};
		var dones = elem.val().split(',');
		for(var i = 0; i < dones.length; i++){
			doneUsers[$.trim(dones[i])] = true;
		}
	}
	function updataePos(elem){
		curPos = elem;
		results.children('li').removeClass('popPos');
		curPos.addClass('popPos');
	}
	function addValue(v,elem){
		var defaultValue = elem.val();
		var tmp = '';
		if(defaultValue.indexOf(',') >= 0){
			tmp = defaultValue.substr(0,defaultValue.lastIndexOf(',')+1)+v;
		}else{
			tmp = v;
		}
		elem.val(tmp);
		results.html('');
		pop.hide();
	}
	return $(this).each(function(){
		$(this).attr('autocomplete','off');
		var outKey = [9,13,38,40];
		$(this).bind('keyup',function(e){
			var newVal = $(this).val();
			switch (e.keyCode) {
			    case 16: // shift
			    case 17: // ctrl
			    case 18: // alt
			    case 20: // caps lock
			    case 33: // page up
			    case 34: // page down
			    case 35: // end
			    case 36: // home
			    case 37: // left arrow
			    case 38: // up arrow
			    case 39: // right arrow
			    case 40: // down arrow
			      		return true;
			
			    case 9:  // tab
			    case 13: // enter
			    case 27: // esc
			     		 return true;
			    default: //all other keys
				    if(newVal.length >= ops.chars){
						quest(newVal,$(this));	
					}else{
						pop.hide();
					}
			}	
		}).bind('keydown',function(e){
			if(e.keyCode == 9 || e.keyCode == 13){
				if(curPos){
					loadDone($(this));
					var tv = curPos.text();
					if(!doneUsers[tv]){
						addValue(tv,$(this));	
					}
				}
				stopDefault(e);
				return false;
			}else if(e.keyCode == 38){
				if(curPos.prev().length > 0){
					return updataePos(curPos.prev());	
				}
				return false;
			}else if(e.keyCode == 40){
				if(curPos.next().length > 0){
					return updataePos(curPos.next());
				}
				return false;
			}
		});
	});
};

function rank(obj){
	var _url = $(obj).attr('href');
	//alert(_url);
	$.ajax({
		type: "GET",
		url: _url,
		success: function(data){
			//alert(data);
			if(data == 0){
				alert("error.");
			}else{
				$(obj).parent().html('('+data+')');
			}
		}
	});
	return false;
}

function changestatus(s){
	$.ajax({
		type: "GET",
		url: s,
		success: function(data){
			//alert(data);
		}
	});
}

function calMini(u){
	$.ajax({
		type: "GET",
		url: u,
		success: function(data){
			//alert(data);
			$('#calendarDiv').html(data);
		}
	});
}

$.fn.calEvent = function(options){
		var defaults={
			pobj: '#calendarTask',
			cobj: '#calendarTaskCt',
			close: '#calendarTaskClose',
			pobjHide: true
		};
		var ops = $.extend(defaults,options);
		var isHide = true;
		var _load = $('<div class="loading"></div>');
		function change(url){
			$.ajax({
				type: "GET",
				url: url,
				cache: true,
				success: function(data){
					$(ops.cobj).html(data);
					$(ops.cobj).hide();
					$(ops.cobj).slideDown(400);
				}
			});
		}
		this.each(function(){
			$(this).click(function(){
				var _url = $(this).attr('href');
				if(ops.pobjHide){
					var _pos = $(this).position();
					if(_pos.left>400) $(ops.pobj).css({top:_pos.top+18+'px',left:(_pos.left-200)+'px'});
					else $(ops.pobj).css({top:_pos.top+18+'px',left:_pos.left+18+'px'});
				}
				if(ops.pobjHide && isHide){
					$(ops.pobj).slideDown(400);
					isHide = false;
				}else{
					$(ops.cobj).html(_load);
				}
				change(_url);
				return false;
			});
		});
		$(ops.close).click(function(){
			$(ops.cobj).html(_load);
			$(ops.pobj).hide();
			isHide = true;
		});
		$(document).click(function(){
			$(ops.cobj).html(_load);
			$(ops.pobj).hide();
			isHide = true;
		});
		$(ops.pobj).click(function(e){
			stopBubble(e);
		});
};

function stopBubble(e){
	if(e && e.stopPropagation){
		e.stopPropagation();	
	}else{
		window.event.cancelBubble = true;	
	}	
}

jQuery.fn.LoadImage=function(scaling,width,height,loadpic){
    if(loadpic==null) loadpic="loading.gif";
	return this.each(function(){
		var t=$(this);
		var src=$(this).attr("src")
		var img=new Image();
		//alert("Loading...")
		img.src=src;
		//自动缩放图片
		var autoScaling=function(){
			if(scaling){
			
				if(img.width>0 && img.height>0){ 
			        if(img.width/img.height>=width/height){ 
			            if(img.width>width){ 
			                t.width(width); 
			                t.height((img.height*width)/img.width); 
			            }else{ 
			                t.width(img.width); 
			                t.height(img.height); 
			            } 
			        } 
			        else{ 
			            if(img.height>height){ 
			                t.height(height); 
			                t.width((img.width*height)/img.height); 
			            }else{ 
			                t.width(img.width); 
			                t.height(img.height); 
			            } 
			        } 
			    } 
			}	
		}
		//处理ff下会自动读取缓存图片
		if(img.complete){
		    //alert("getToCache!");
			autoScaling();
		    return;
		}
		$(this).attr("src","");
		var loading=$("<img alt=\"Loading...\" title=\"Loading...\" src=\""+loadpic+"\" />");
		
		t.hide();
		t.after(loading);
		$(img).load(function(){
			autoScaling();
			loading.remove();
			t.attr("src",this.src);
			t.show();
			//alert("finally!")
		});
		
	});
}

$(function(){//chat隐藏
	$("#imTinybar").hide();
})
var chatstatus=0;
function chatOpen(){
	try{
		if($("#imTinybar").css("display")=='none'){
			$("#imTinybar").show();
			i_im_setShow('imbar');
			setOnShowPara('imbar');
		}else if(chatstatus==0){
			//$("#imTinybar").show();
			i_im_setShow('imbar');
			setOnShowPara('imbar');
			chatstatus=1;
		}else{
			$("#imTinybar").hide();
			chatstatus=0;
		}
	}catch(e){}
}
function chatWith(uid){
	try{
		i_im_talkWin(uid,'imWin');
	}catch(e){}
}
/*切换多次后有问题
function changeLan(u,l){
	//alert(u+'/l/'+l);
	if(u.toString().indexOf('index.php')===-1) _url=u+'?l='+l;
	else _url=u+'/l/'+l;
	$.ajax({
		type: "GET",
		url: _url,
		success: function(data){
			alert(data);
			//document.write(data);
			window.location.reload();
		}
	});
}*/