/*
***************************
*  17k common javascript  *
*  dependent jquery-1.4.2 *
*  version:1.0            *
*  coder:BennyTian        *
*  date:2011/04/18        *
***************************
*/

if (!window.K17) {
	window.K17 = {};
}
window._ = window.K17;

/* @example _.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example _.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example _.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example _.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 */
K17.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
		var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * @description: 自动往上滚动
 * @example _.autoScroll([{"id":"test","time":1000,"row":2},{"id":"test2","time":2000}]);
 * @example _.autoScroll({"id":"test","time":1000,"row":2});
 * @id	:element's id
 * @time:scroll interval time
 * @row	:scroll rows []
 */
K17.autoScroll = function(obj){ 
	if((typeof obj)!="object"){
		alert("params error...");return false;
	}
	var elements = [];
	if($.isArray(obj)){
		elements = obj;
	}else{
		elements.push(obj);	
	}
	
	var setScrollInterval = function(){
		if(elements.length==0){
			alert("error...");return false;
		}
		for(var i=0;i<elements.length;i++){
			var elem = 	elements[i];
			if(K17.isEmpty(elem.id) || K17.isEmpty(elem.time) ||(!K17.isEmpty(elem.row)&& !K17.isNumber(elem.row))){
				alert("params error...");continue;
			}
			if(K17.isEmpty(elem.row)){
				elem.row = 1;	
			}
			setInterval("K17.autoScroll.setAutoScroll('"+elem.id+"',"+elem.row+")",elem.time);
		}
	};
	
	K17.autoScroll.setAutoScroll = function(id,row){
		var ul = $("#"+id).find("ul:first");
		var firstLi = ul.find("li:first");
		var height = 25;
		var liHeight = getLiHeight(firstLi);;
		var scrollLis = firstLi;
		if(liHeight>0){
			height = liHeight * row;
		}else{
			height*=row;
		}
		if(row>1){
			scrollLis = ul.find("li:lt("+row+")");
		}
		height = -height+"px";
		ul.animate({marginTop:height},500,function(){
			ul.css({"marginTop":"0px"});
			scrollLis.appendTo(ul);
		});
	};
	
	var getLiHeight = function(li){
		var height = 0;
		var liHeight = parseInt(li.css("height"));
		var marginTop = parseInt(li.css("marginTop"));
		var marginBottom = parseInt(li.css("marginBottom"));
		var paddingTop = parseInt(li.css("paddingTop"));
		var paddingBottom = parseInt(li.css("paddingBottom"));
		var borderTopWidth = parseInt(li.css("borderTopWidth"));
		var borderBottomWidth = parseInt(li.css("borderBottomWidth"));
		if(K17.isNumber(liHeight)){
			height+= liHeight;
		}
		if(K17.isNumber(marginTop)){
			height+= marginTop;
		}
		if(K17.isNumber(marginBottom)){
			height+= marginBottom;
		}
		if(K17.isNumber(paddingTop)){
			height+= paddingTop;
		}
		if(K17.isNumber(paddingBottom)){
			height+= paddingBottom;
		}
		if(K17.isNumber(borderTopWidth)){
			height+= borderTopWidth;
		}
		if(K17.isNumber(borderBottomWidth)){
			height+= borderBottomWidth;
		}
		return height;
	};
	setScrollInterval();
};

K17.isEmpty = function(value){
	return (typeof value) == 'undefined' || $.trim(value+"")=="" || value==null;
};

K17.isUndefined = function(value){
	return (typeof value) == 'undefined';
};

K17.isNumber = function(value){
	return !isNaN(value);
};

/* 
 * @description: Ajax跨域获取json
 * @example _.getJSON("http://passport.17k.com/login.action",{"name":"BennyTian","password":"123456"},"getLoginInfo");
 */
K17.getJSON = function(url,params,callbackName){
	if(K17.isEmpty(url)){
		alert("url is null...");return false;	
	}
	var callbackParamName = "jsonp";
	var isAppend = url.indexOf("?")!=-1 ;
	var callback = null;
	
	if(!K17.isEmpty(params)){
		if($.isPlainObject(params)){
			var param = jQuery.param(params);
			if(isAppend){
				param = "&"+param;
			}else{
				param = "?"+param;	
			}
			url += param;
		}else if(typeof params =="string" && K17.isEmpty(callbackName)){
			callback = params;
		}else{
			alert("params error..."); return false;
		}
	}
	if(!K17.isEmpty(callbackName)){
		callback = callbackName;
	}
	if(!K17.isEmpty(callback)){
		if(url.indexOf("?")!=-1){
			url += "&"+callbackParamName+"="+callback;
		}else{
			url += "?" +callbackParamName+"="+callback;	
		}
	}
	if(url.indexOf("?")!=-1){
		url += "&randm="+Math.random();
	}else{
		url += "?randm="+Math.random();;	
	}
	if (!document.body){
		document.write("<script type=\"text/javascript\" src=\'"+url+"\' ><\/script>");
	}else{
		var script = document.createElement("script"); //只能使用dom这种方式创建js,用jquery在ie6下不兼容
	  	script.charset = "utf-8";
	  	script.language = "javascript"; 
		script.type = "text/javascript";
	    script.src = url;
	   	document.body.appendChild(script);
	}
};

/*
 * @description: 设为首页
 */
K17.homepage = function(){
	var domain = "http://www.17k.com/";
	if(document.all){
		document.body.style.behavior = 'url(#default#homepage)';
		document.body.setHomePage(domain);
	}else if(window.sidebar){
		if(window.netscape){
			try{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			}catch(e){
				alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
				return;
			}
		}
		var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
		prefs.setCharPref('browser.startup.homepage', domain);
	}	
};

/*
 * @description: 加为收藏
 */
K17.favorite = function(){
	var title = "一起看小说网_www.17k.com";
	var domain = "http://www.17k.com/";
	try{
		window.external.addFavorite(domain, title);
	}catch(e){
		try{
			window.sidebar.addPanel(title, domain, "");
		}catch(e){
			alert("亲,您的游览器不支持自动加入收藏哦,请尝试 Ctrl+D 手动添加吧.");
		}
	}
};

/*
 * @description: 切换,可实现Ajax延迟加载内容,主要针对延迟加载碎片
 * @example:_.iswitch("按钮的id前缀","内容部分div的id前缀","按钮选中的class","按钮没选中的class")
 */
K17.iswitch = function(buttonIdPrefix,divIdPrefix,selectClass,unselectClass,defaultSelectIndex){
	if(K17.isUndefined(buttonIdPrefix)||K17.isUndefined(divIdPrefix)||K17.isUndefined(selectClass)||K17.isUndefined(unselectClass)){
		alert("params error...");return false;	
	}
	var buttons = $("[id^="+buttonIdPrefix+"]");
	var divs = $("[id^="+divIdPrefix+"]");
	buttons.live("click",function(){
		var currentButton = $(this);
		var index = buttons.index(currentButton);
		var currentDiv = $(divs.get(index));
		$.each(buttons,function(i,e){
			$(e).attr("class",unselectClass);
		});
		currentButton.attr("class",selectClass);
		$.each(divs,function(i,e){
			$(e).hide();
		});
		if(!K17.isEmpty(currentButton.attr("url"))){ //lazy load
			if(K17.isEmpty(currentDiv.html())){
				try{
					currentDiv.html("<div style=\"padding-top:5px;margin-left:20px;\"><img style=\"width:16px;height:16px;\" src=\"http://img.17k.com/style/common/loginload.gif\" /> 加载中,请稍后...</div>");
					$.get(currentButton.attr("url"),function(data){
						currentDiv.html(data);
					});	
				}catch(e){alert("ajax lady load error");}
			}
		}
		currentDiv.show();
	});
	if(K17.isNumber(defaultSelectIndex)){
		if(defaultSelectIndex<0 || defaultSelectIndex>buttons.length-1){
			defaultSelectIndex = 0;
		}
		$.each(divs,function(i,e){
			$(e).hide();
		});
		$.each(buttons,function(i,e){
			$(e).attr("class",unselectClass);
		});
		$(buttons.get(defaultSelectIndex)).attr("class",selectClass);
		$(divs.get(defaultSelectIndex)).show();
	}
};

/*
 * @description: 自动提示搜索
 * @example:_.isearch("文本框ID","显示结果div的ID","代理的iframeProxy的ID")
 */
document.domain = "17k.com";
K17.isearch = function(searchId,suggestId,iframeProxyId){
	if(K17.isEmpty(searchId)||K17.isEmpty(suggestId)||K17.isEmpty(iframeProxyId)){
		alert("params error...");return false;	
	}
	var tipMessage = "作者名/作品名/作品关键字";
	$("#"+searchId).val(tipMessage);
	var proxy = $("#"+iframeProxyId).get(0).contentWindow;
	
	$("#"+searchId).keydown(function(e){
		var evt = window.event||e;
		proxy.beKeyDown(evt);
	});

	$("#"+searchId).keyup(function(e){
		var evt = window.event||e;
		var searchKey = $("#"+searchId).val();
  		if(K17.isEmpty(searchKey)){
			searchKey = "";
		}
    	proxy.searchSuggest(searchKey,escape(searchKey),evt);
	});

	$("#"+searchId).focus(function(){
		if($("#"+searchId).val()==tipMessage){
			$("#"+searchId).val("");
		}
	});

	$("#"+searchId).blur(function(){
		if(K17.isEmpty($("#"+searchId).val())){
			$("#"+searchId).val(tipMessage);
		}
	});
	
	$("body").live("click",function(){
		$("#"+suggestId).html("");
		$("#"+suggestId).css({"visibility":"hidden"});
	});

	var resultDivs = $("#"+suggestId+">div[id^=item]");
	resultDivs.live("mouseover",function(){
		proxy.suggestOver(this);
	});
	resultDivs.live("mouseout",function(){
		proxy.suggestOut(this);
	});
	resultDivs.live("click",function(){
		var searchKey = $(this).find("td:eq(0)").html();
		$("#"+searchId).val(searchKey);
		$("#"+suggestId).html("");
		$("#"+suggestId).css({"visibility":"hidden"});
	});
	/***新搜索上线 临时解决方案***/
	var searchForm = $("#"+iframeProxyId).parent();
	searchForm.submit(function(){
		$("#"+searchId).attr("name","c.q");
		searchForm.attr("method","get");
		searchForm.attr("action","http://search.17k.com/search.xhtml");
		return true;
	});
};

K17.isLogined = function(){
	return K17.cookie("sso.ssoId")!=null ;
};

K17.initCookieTimeOut = 5000;
K17.isInvokeInitCookie = false;
K17.getLoginInfo = function(){
	var getCookie = function(){
		var info = K17.cookie("uin").split("|");
		var userInfo = {};
		userInfo.userId=info[0];
		userInfo.nickName=info[1];
		userInfo.isAuthor = info[2];
		userInfo.flower = K17.cookie("tfn");
		userInfo.pkVote = K17.cookie("month_pk_count");
		for(attr in userInfo){
			if(K17.isEmpty(userInfo[attr])){
				return null;
			}
		}
		return userInfo;
	};
	var userInfo = null;
	try{
		userInfo = getCookie();
	}catch(e){}
	try{
		if(userInfo==null && !K17.isInvokeInitCookie){
			K17.isInvokeInitCookie = true;
			K17.getJSON("http://passport.17k.com/initUserCookie.action");
		}
	}catch(ee){}
	return userInfo;
};

K17.logout = function(){
	window.location="http://passport.17k.com/logout.jsp?url="+encodeURIComponent(window.location);
};

//Png logo 透明
K17.alphaLogo = function(){
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
	if (itsAllGood) {
		var logo = $("#top .logo>a");
		if(logo.length>0){
			logo = logo.get(0);
			var bg = logo.currentStyle.backgroundImage;
			if (bg){
				if (bg.match(/.png/i) != null){
					var mypng = bg.substring(5,bg.length-2);
					logo.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+mypng+"', sizingMethod='crop')";
					logo.style.backgroundImage = "url('')";
				}
			}
		}
	};
};

K17.hover = function(elem,elemContent){
	if(K17.isEmpty(elem)||K17.isEmpty(elemContent)){
		alert("params error...");return false;
	}
	elem = $("#"+elem);
	elemContent = $("#"+elemContent);
	elemContent.hide();
	var hide = function(obj){
		obj.hide();
	};
	var time = {};
	elem.hover(function(){
		clearTimeout(time);
		elemContent.show();
	},function(){
		time = setTimeout(function(){elemContent.hide();},500);
	});
	elemContent.hover(function(){
		clearTimeout(time);
	},function(){
		time = setTimeout(function(){elemContent.hide();},500);
	});
};

K17.dialog = function(title,content,width,height,cssName){
	
	if($("#floatBoxBg").length<=0){
		var temp_float="<div id=\"floatBoxBg\" style=\"filter:alpha(opacity=30);opacity:0.3;mozopacity:0.3;-moz-opacity:0.3;background-color:#000;position:absolute;top:0;left:0;\"></div>";
			temp_float+="<div id=\"floatBox\" class=\"floatBox\" style=\"position:absolute;top:50px;left:40%;padding:5px;background:url(http://img.17k.com/style/common/dialog_bg.png);width:400px;\">";
  				temp_float+="<div class=\"popup\">";
  					temp_float+="<div class=\"popup_tit\">";
  						temp_float+= "<h2 id=\"title\"></h2>";
  						temp_float+= "<span class=\"more\"><a href=\"javascript:K17.dialog.closebox();\"><img src=\"http://img.17k.com/style/common/dialog_close.gif\" /></a></span>";
  					temp_float+="</div>";
  					temp_float+="<div id=\"content\" class=\"popup_con\"></div>";
  				temp_float+="</div>";
			temp_float+="</div>";
			
		var style = document.createElement("link");
		style.rel = "stylesheet";
		style.type = "text/css";
		style.href = "http://img.17k.com/style/popup/popup.css";
	   	document.body.appendChild(style);
	   	
		$("body").append(temp_float);
	}
	$("#floatBox #title").html(title);
	contentType=content.substring(0,content.indexOf(":"));
	content=content.substring(content.indexOf(":")+1,content.length);
	switch(contentType){
  		case "url":
  			content_array=content.split("?");
		  	$.ajax({
				type:content_array[0],
				url:content_array[1],
				data:content_array[2],
				error:function(){
			  		$("#floatBox #content").html("error...");
				},
    			success:function(html){
      				$("#floatBox #content").html(html);
    			}/*,async: false*/
  			});
 			break;
  		case "text":
  			$("#floatBox #content").html("<p class=\"p_t1\">"+content+"</p><div class=\"popup_btn\"><input type=\"button\" class=\"p_btn02\" value=\"关闭\" onclick=\"K17.dialog.closebox();\"/></div>");
 			 break;
  		case "id":
  			$("#floatBox #content").html($("#"+content+"").html());
  			break;
 		case "iframe":
  			$("#floatBox #content").html("<iframe src=\""+content+"\" width=\"100%\" height=\""+(parseInt(height)-30)+"px"+"\" scrolling=\"auto\" frameborder=\"0\" marginheight=\"0\" marginwidth=\"0\"></iframe>");
	}
	$("#floatBox .popup").css({"width":parseInt(width)-5+"px","height":(height=="auto"?185:parseInt(height))-5+"px"});	
	$("#floatBoxBg").show();
	$("#floatBox").attr("class","floatBox "+cssName);
	$("#floatBox").css({"width":width,"height":height});

	K17.dialog.closebox = function(){
		$("#floatBoxBg").hide();
		$("#floatBox #content").html("");
		$("#floatBox").hide();
		$(window).unbind("resize");
		$(window).unbind("scroll");
	};
	
	K17.dialog.reset = function(width,height){
		var windowHeight = $(window).height();
		var windowWidth = $(window).width();
		var elementHeight = height=="auto"?185:parseInt(height);
		var elementWidth = parseInt(width);
		var windowTop = $(window).scrollTop();
		var windowLeft = $(window).scrollLeft();
		var elementTop = windowTop + (elementHeight > windowHeight ? windowHeight/10 : (windowHeight - elementHeight)/2);
		var elementLeft = windowLeft + (elementWidth > windowWidth ? 0 : (windowWidth - elementWidth)/2);
		$("#floatBox").css({"left":elementLeft+"px","top":elementTop+"px"});
		$("#floatBoxBg").css({"height":$(document).height()+"px","width":windowWidth+windowLeft+"px"});
	};
	$(window).bind("resize",function(){setTimeout("K17.dialog.reset('"+width+"','"+height+"')",50);});
	$(window).bind("scroll",function(){setTimeout("K17.dialog.reset('"+width+"','"+height+"')",150);});
	K17.dialog.reset(width,height);
	$("#floatBox").slideDown("slow");
};

K17.messages = function(messageImgId,messageBoxId,userMessageNumId,userMessageContentId){
	if(K17.isEmpty(messageImgId) || K17.isEmpty(messageBoxId) || K17.isEmpty(userMessageNumId)||K17.isEmpty(userMessageContentId)){
		alert("params error..."); return false;	
	}
	K17.getMessages = function(){
		var url = "http://passport.17k.com/findpass/getMsgbyUserId.action";
		try{
			K17.getJSON(url,"K17.messageCallback");
		}catch(e){}
	};
	K17.messageCallback = function(data){
		if(data.result){
			try{
				if(!K17.isEmpty(data.content)){
					var message = eval("("+data.content+")");
					if(message.count-0>0){
						$("#"+messageImgId).show();
						$("#"+userMessageNumId).html(message.count);
						$("#"+userMessageContentId).html(message.title);
						$("#"+userMessageContentId).live("click",function(){K17.messageClick(messageImgId,messageBoxId);});
					}else{
						$("#"+messageImgId).hide();
						$("#"+messageBoxId).hide();
						$("#"+userMessageNumId).html("0");
						$("#"+userMessageContentId).html("");
					}
				}
			}catch(e){alert(e);};
		}
	};
	K17.messageClick = function(messageImgId,messageBoxId){
		$("#"+messageImgId).hide();
		$("#"+messageBoxId).hide();
		window.open("http://user.17k.com/myMessages/showMessages.action","_blank");
	};
	setTimeout(K17.getMessages,3*1000);
	//setInterval(K17.getMessages,60*1000);
};

K17.saveReferer = function(){
	var cookieName = "K17_user_Referer";
	var cookieExpires = 30;
	var getDomain = function(url){
		try{
			var scheme = "http://";
			var schemeLength = 7;
			if(/^http\:\/\//.test(url.toLowerCase())){
				scheme = "http://";
				schemeLength = 7;
			}else if(/^https\:\/\//.test(url.toLowerCase())){
				scheme = "https://";
				schemeLength = 8;
			}else if(/^ftp\:\/\//.test(url.toLowerCase())){
				scheme = "ftp://";
				schemeLength = 6;
			}
			var domain = url.substring(url.indexOf(scheme)+schemeLength);
			domain = domain.substring(0,domain.indexOf("/"));
			return domain;
		}catch(e){
			return null;
		}
	};
	var saveCookie = function(referrer){
		if(K17.isEmpty(referrer)){
			alert("params error...");
			return false;
		}
		//var cookValue = encodeURIComponent(referrer);
		var cookieValue = referrer;
		K17.cookie(cookieName, cookieValue,{expires: cookieExpires, path: '/', domain: '17k.com' });
	};
	
	if(!K17.isLogined()){
		var referrer = document.referrer;
		if(!K17.isEmpty(referrer)){
			var domain = getDomain(referrer);
			if(domain!=null && domain.indexOf(".17k.com")==-1){
				saveCookie(referrer);
			}
		}
	}else{
		K17.cookie(cookieName,null,{path: '/', domain: '17k.com' });
	}
};
K17.saveReferer();
