var timer;
function scrollwindow() {
    window.scrollBy(0, 1)
}

function ToJson(str) {
	return eval('(' + str + ')');
}

function ChangeSize(obj) {
    $('.sltFontColor').removeClass('sltFontColor');
    $(obj).addClass('sltFontColor');
    fontSize = $(obj).attr('fontSize');
    WriteCookis(null, fontSize, null);
	SetFontSize(fontSize);
}

function ChangeFont(obj) {
	font = $(obj).attr('font');
	$('.sltFontFamilyColor').removeClass('sltFontFamilyColor');
	$(obj).addClass('sltFontFamilyColor');
	WriteCookis(null, null, font);
	SetFontFamily(font);
}

function ChangeBgColor(obj) {
    $('.sltColorPanel').removeClass('sltColorPanel');
    $(obj).addClass('sltColorPanel');
    bgColor = $(obj).attr('color');
    WriteCookis(bgColor, null, null);
    SetBgColor(bgColor);
}

if (typeof (JCookies) == 'undefined') {
    JCookis = {
        EnCode: function(text) {
            return escape(text);
        },
        DeCode: function(text) {
            return unescape(text);
        },
        Add: function(key, obj, timeOut) {
            var valType = typeof (obj);
            if (valType == 'string' | valType == 'number') {
                obj = this.EnCode(obj);
            }
            var cookis = key + '=' + obj + ';path=/';
            if (timeOut != null) {
                cookis += ";expires=" + this.TimeOut(timeOut);
            }
            document.cookie = cookis;
        },
        Item: function(key) {
            var cookisInfo = document.cookie;
            var iStartIndex = cookisInfo.indexOf(key);
            if (iStartIndex == -1)
                return null;
            var iEndIndex = cookisInfo.indexOf(';', iStartIndex);
            if (iEndIndex < iStartIndex)
                iEndIndex = cookisInfo.length;
            var cookis = cookisInfo.substring(iStartIndex + key.length + 1, iEndIndex);
            return this.DeCode(cookis);
        }
    };
}
function ReadCookis() {
    var data = ToJson(JCookis.Item('ReadPageSetting'));
    if (data == null) { data = {}; }
    if (data.BgColor == null) { data.BgColor = '#E7F4FE'; }
    if (data.FontSize == null) { data.FontSize = '16px'; }
    return data;
}

function WriteCookis(bgColor, fontSize, fontFamily) {
    var oldData = ReadCookis();
    var newData = {};
    if (bgColor != null) {
        newData.BgColor = bgColor;
    }
    if (fontSize != null) {
        newData.FontSize = fontSize;
    }
    if (fontFamily != null) {
    	newData.FontFamily = fontFamily;
    }
    var saveData = '{ BgColor: "' + ((newData.BgColor == null) ? oldData.BgColor : newData.BgColor) + '", FontSize:"' + ((newData.FontSize == null) ? oldData.FontSize : newData.FontSize) + '", FontFamily:"' + ((newData.FontFamily == null) ? oldData.FontFamily : newData.FontFamily) +'" }';
    JCookis.Add('ReadPageSetting', saveData);
}


function InitColorPanel() {
    document.write(GetColorHtml('#FFFFFF'));
    document.write(GetColorHtml('#e9faff'));
    document.write(GetColorHtml('#E7F4FE'));
    document.write(GetColorHtml('#CDD1FF'));
    document.write(GetColorHtml('#ffffed'));
    document.write(GetColorHtml('#81B757'));
    document.write(GetColorHtml('#fcefff'));
    document.write(GetColorHtml('#F0F0F0'));
}

function LoadClientParm() {
    var saveParm = ReadCookis();
    if (saveParm != null) {
        if (saveParm.BgColor != null) {
            $('.sltFontColor').removeClass('sltFontColor');
            $('#bgColorPanel>:[color="' + saveParm.BgColor + '"]').addClass('sltColorPanel');
        }
        if (saveParm.FontSize != null) {
            $('.sltColorPanel').removeClass('sltFontColor');
            $('#fontSizePanel>:[fontSize="' + saveParm.FontSize + '"]').addClass('sltFontColor');
        }
        if (saveParm.FontFamily != null) {
        	$('.sltFontFamilyColor').removeClass('sltFontFamilyColor');
        	$('#fontFamilyPanel>:[font="' + saveParm.FontFamily + '"]').addClass('sltFontFamilyColor');
        }
    }
}

function GetColorHtml(color) {
    return  "<div onclick='javascript:ChangeBgColor(this);' class='colorPanel' style='background-color:" + color + ";' color='" + color + "'></div>";
}

function InitFontSizePanel() {
	document.write(GetFontSizeHtml('22px', '特大'));
    document.write(GetFontSizeHtml('18px', '大'));
    document.write(GetFontSizeHtml('14px', '中'));
    document.write(GetFontSizeHtml('12px', '小'));
}

function GetFontSizeHtml(fontSize, txt) {
    return "<a href='javascript:;' onclick='ChangeSize(this)' fontSize='" + fontSize + "' style='margin-left:3px; padding:2px;'>" + txt + "</a>";
}

function InitFontPanel() {
	document.write(GetFontHtml('宋体', '宋体'));
	document.write(GetFontHtml('黑体', '黑体'));
	document.write(GetFontHtml('微软雅黑', '微软雅黑'));
	document.write(GetFontHtml('楷体', '楷体'));
}

function GetFontHtml(font, txt) {
    return "<a href='javascript:;' onclick='ChangeFont(this)' font='" + font + "' style='margin-left:3px; padding:2px;'>" + txt + "</a>";
}

function SetFontSize(size) {
	$("#content p").css({fontSize:size});
}

function SetFontFamily(font) {
	$("#content p").css({fontFamily:font});
}

function SetBgColor(color) {
	$('body').css({backgroundColor:color});
}

function pannel() {
	document.writeln("<div class=\"changecolor\">");
	document.writeln("<span style=\"float:left; width:120px;\">选择背景颜色：</span> ");
	document.writeln("<span id=\"bgColorPanel\">");
	InitColorPanel();
	document.writeln("</span>");
	document.writeln("");
	document.writeln("<span id=\"fontSizePanel\" class=\"changesize\">选择字号：");
	InitFontSizePanel();
	document.writeln("</span>");
	document.writeln("<span id=\"fontFamilyPanel\">选择字体：");
	InitFontPanel();
	document.writeln("</span>");
	document.writeln("</div>");
}

function notice() {
	document.writeln("<br/><font size=\"3\" color=\"red\">为了维持运营成本，书城加入一些弹出窗口广告，６个小时内最多弹出４０次，弹出４０次之后，不再弹出<br></font>");
}

$(function() {
	document.onselectstart = function() { return false;};
	document.oncontextmenu = function() { return false;};
	document.onmousedown = function() { return false;};
	$('#topbgdiv').hide();
	
	var PageSetting = ReadCookis();
	var initBgColor = '#FFFFFF';
	var initFontSize = '18px';
	var initFontFamily = '宋体';

	if ('' != PageSetting.BgColor) {
		initBgColor = PageSetting.BgColor;
	}
	if ('' != PageSetting.FontSize) {
		initFontSize = PageSetting.FontSize;
	}
	if ('' != PageSetting.FontFamily) {
		initFontFamily = PageSetting.FontFamily;
	}

	SetFontSize(initFontSize);
	SetBgColor(initBgColor);
	SetFontFamily(initFontFamily);
	$('#content').bind('copy', function() {setTimeout(function() {
        var t = clipboardData.getData("text");
        if (t) {
            var r = '本文转自至酷书城 ' + location.href;
            var l = t.length;
            var m = parseInt(Math.random() * l);
            var v = t.substring(0, m) + r;
            var w = t.substring(m, l);
            clipboardData.setData("text", v + w)
        }
    },
    100)});

	$(document).bind('mousedown', function() { clearInterval(timer);});
	$(document).bind('dblclick', function() { timer = setInterval("scrollwindow()", 300 / 5);});
	
	$('#up').click(function() {
		if(jQuery.browser.safari) {
			//这里判断浏览器是否为safari
			jQuery('body').animate({scrollTop:0}, 'slow');
			return false;//返回false可以避免在原链接后加上#
		} else {
			jQuery('html').animate({scrollTop:0}, 'slow');
			return false;
	    }

	});

	$('#down').click(function() {
		if(jQuery.browser.safari) {
			//这里判断浏览器是否为safari
			jQuery('body').animate({scrollTop:$('#footerud').offset().top}, 'slow');
	      	return false;//返回false可以避免在原链接后加上#

		} else {
			jQuery('html').animate({scrollTop:$('#footerud').offset().top}, 'slow');
	      	return false;
	    }
	});
});

function addProgress(bookId, chapterId) {
	if (true !== isLogin) {
		alert('请先登陆！');
		return false;
	}
	if (isNaN(bookId) || isNaN(chapterId)) {
		alert('非法请求');
		return false;
	}

	$.ajax({
		url: progressSaveUrl,
		type: 'GET',
		data: 'bid='+bookId+'&cid='+chapterId,
		dataType: 'json',
		success: function(msg) {
			alert(msg.msg);
		}
	});
}

var reportView = false;
var progressView = false;
function report(e, title) {
	if (true !== isLogin) {
		alert('请先登陆！');
	} else {
		createWindows('错误报告','','400px','320px','errdiv',e);
		$("#errdiv .con").html('<br/>地址:<span id="eUrl">'+location.href+'</span><br/><br/>标题:<span id="eTitle">'+title+'</span><br/><br/>错误类型:<select name="type" id="type"><option value="2">书城更新慢了</option><option value="1">章节重复</option><option value="3">内容不对</option><option value="4">无法阅读</option></select><br/><br/>出错说明:<br/><textarea name="textarea" cols="40" rows="5" id="eRemark"></textarea><br/><br/><input type="button" onclick="postReport()" name="Submit" value="提交" /><span id="emsg"></span>');
		if (false === reportView) {
			var top = parseInt($("#errdiv").css('top'));
			var left = parseInt($("#errdiv").css('left'));
			var newt = top - 350;
			var newl = left - 250;
			if(newt<1) newt = 1;
			if(newl<1) newl = 1;
			$("#errdiv").css({'top':newt+'px','left':newl+'px'});
			reportView = true;
		}
	}
}

function postReport(bid, cid) {
	if (true !== isLogin) {
		alert('请先登陆！');
	} else {
		var type = $('#type').val();
		var eRemark = $('#eRemark').val();
		if ('' == eRemark) {
			//alert('请输入"出错说明"');
			//return false;
		}

		$.ajax({
			url: reportUrl,
			type: 'POST',
			data: 'remark='+eRemark+'&type='+type,
			dataType: 'json',
			beforeSend: function() {$('#emsg').html('<img src="/images/loding.gif" />信息提交中，请稍后.....')},
			success: function(msg) {
				alert(msg.msg);
				if (1 == msg.status) {
					$('#errdiv').hide();
				} else {
					$('#emsg').html('');
				}
			}
		});
	}
}

function myProgress(e, page) {
    if(isLogin) {
    	createWindows('我的阅读进度','<img src="/images/loding.gif" />正在载入....','730px','auto','myprogressdiv',e);
    	if (!progressView) {
			var newt = $(document).scrollTop();
			var newl = $(document).scrollLeft();
			if(newt<1) newt = 1;
			if(newl<1) newl = 1;
			$("#myprogressdiv").css({'top':newt+'px','left':newl+'px'});
			progressView = true;
    	}
		
    	$.ajax({
    		url: progressUrl,
    		type: 'GET',
            data: 'page='+page,
    		dataType: 'html',
    		success: function(msg) {
                $('#myprogressdiv .con').html(msg);
    		}
    	});
	} else {
		alert('请先登陆！');
	}
}

function deleteProgress(bid) {
	if (!confirm('确定要下架吗？')) {
		return false;
	}
	$.ajax({
		url: progressDeleteUrl + '&bid=' + bid,
		type: 'GET',
		success: function(msg) {
			$('#bid'+bid).hide();
		}
	});
}
/**
var num = 40;
var dtime = 6*3600*1000;
var ifend = parseInt(getCookie('isend') ? getCookie('isend') : 0);
var td = new Date();
try {
    if(ifend == 0) {
    	var preal = parseInt(getCookie('tnum') ? getCookie('tnum') : 0);
    	if(preal < num) {
    		setCookie('tnum', preal + 1, td.getTime() + 1800 * 1000);
    		document.writeln("<script language=\"javascript\" src=\"http://www.ubcpm.com/C.html?P=5673&T=1&A=0&k=1&Z=0&S=60&N=1\">\<\/script>");
    	} else {
    		setCookie('isend', 1, td.getTime() + dtime);
    	}
    }
} catch(e) {}
/**/
$(document).keydown(function(event) {
	event = event || window.event;
	if (event.keyCode == 37) {
		if($('#previouschapter').attr('href') != undefined) {
			window.location = $('#previouschapter').attr('href');
		}
    };
	if (event.keyCode == 39) {
    	if($('#nextchapter').attr('href') != undefined) {
    		window.location = $('#nextchapter').attr('href');
    	}
    };
    if (event.keyCode == 13) {
    	if($('#enter').attr('href') != undefined) {
    		window.location = $('#enter').attr('href');
    	}
    };
});