﻿/* datas */

var max_user;
var BASE64={
    /**
     * 此变量为编码的key，每个字符的下标相对应于它所代表的编码。
     */
    enKey: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
    /**
     * 此变量为解码的key，是一个数组，BASE64的字符的ASCII值做下标，所对应的就是该字符所代表的编码值。
     */
    deKey: new Array(
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
        -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
        -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
    ),
    /**
     * 编码
     */
    encode: function(src){
        //用一个数组来存放编码后的字符，效率比用字符串相加高很多。
        var str=new Array();
        var ch1, ch2, ch3;
        var pos=0;
       //每三个字符进行编码。
        while(pos+3<=src.length){
            ch1=src.charCodeAt(pos++);
            ch2=src.charCodeAt(pos++);
            ch3=src.charCodeAt(pos++);
            str.push(this.enKey.charAt(ch1>>2), this.enKey.charAt(((ch1<<4)+(ch2>>4))&0x3f));
            str.push(this.enKey.charAt(((ch2<<2)+(ch3>>6))&0x3f), this.enKey.charAt(ch3&0x3f));
        }
        //给剩下的字符进行编码。
        if(pos<src.length){
            ch1=src.charCodeAt(pos++);
            str.push(this.enKey.charAt(ch1>>2));
            if(pos<src.length){
                ch2=src.charCodeAt(pos);
                str.push(this.enKey.charAt(((ch1<<4)+(ch2>>4))&0x3f));
                str.push(this.enKey.charAt(ch2<<2&0x3f), '=');
            }else{
                str.push(this.enKey.charAt(ch1<<4&0x3f), '==');
            }
        }
       //组合各编码后的字符，连成一个字符串。
        return str.join('');
    },
    /**
     * 解码。
     */
    decode: function(src){
        //用一个数组来存放解码后的字符。
        var str=new Array();
        var ch1, ch2, ch3, ch4;
        var pos=0;
       //过滤非法字符，并去掉'='。
        src=src.replace(/[^A-Za-z0-9\+\/]/g, '');
        //decode the source string in partition of per four characters.
        while(pos+4<=src.length){
            ch1=this.deKey[src.charCodeAt(pos++)];
            ch2=this.deKey[src.charCodeAt(pos++)];
            ch3=this.deKey[src.charCodeAt(pos++)];
            ch4=this.deKey[src.charCodeAt(pos++)];
            str.push(String.fromCharCode(
                (ch1<<2&0xff)+(ch2>>4), (ch2<<4&0xff)+(ch3>>2), (ch3<<6&0xff)+ch4));
        }
        //给剩下的字符进行解码。
        if(pos+1<src.length){
            ch1=this.deKey[src.charCodeAt(pos++)];
            ch2=this.deKey[src.charCodeAt(pos++)];
            if(pos<src.length){
                ch3=this.deKey[src.charCodeAt(pos)];
                str.push(String.fromCharCode((ch1<<2&0xff)+(ch2>>4), (ch2<<4&0xff)+(ch3>>2)));
            }else{
                str.push(String.fromCharCode((ch1<<2&0xff)+(ch2>>4)));
            }
        }
       //组合各解码后的字符，连成一个字符串。
        return str.join('');
    }
}
function utf16to8(str) {
    var out, i, len, c;

    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
	c = str.charCodeAt(i);
	if ((c >= 0x0001) && (c <= 0x007F)) {
	    out += str.charAt(i);
	} else if (c > 0x07FF) {
	    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
	    out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
	    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
	} else {
	    out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
	    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
	}
    }
    return out;
}

/* pre functions */
function preSearch(evt) {
	evt = evt || window.event;
	if (evt.keyCode == 13)
		doSearch();
}
function preLogin(evt) {
	evt = evt || window.event;
	if (evt.keyCode == 13)
		doLogin();
}

/* do functions */
function doSearch() {
	var kw = $('search-kw').value;
	if (kw.length == 0) {
		alert('please input the keywords');
		return;
	}
	var engine = $('search-engine').current || 'all';
	//window.location = '/' + CURRENT_LANGUAGE + '/search?keyword=' + encodeURIComponent(kw+engine) + '&page=1';
	window.location = '/' + CURRENT_LANGUAGE + '/search/'+engine +'/' + BASE64.encode(utf16to8(kw));
	//var engine = $('search-engine').current || 'all';
	//window.location = '/' + CURRENT_LANGUAGE + '/search/' + engine + '/' + kw + '/1';
}
function doLogin() {
	var pp = $('login-pp').value;
	var pw = $('login-pw').value;
	if (pp + pw == '') {
		alert('please input your passport and password!');
		return;
	}
	postRequest(
		'/checklogin/rand'+rand(),
		'email=' + $encode(pp) + '&password=' + $encode(pw),
		function (ret) {
			if (ret.readyState == 4 && ret.status == 200) {
				try {
					eval('(' + ret.responseText + ')');
				} catch(e) {
					alert('Failed');return;
				}
				if (!max_user.nickname) {
					alert('Failed');return;
				}
				$('username').innerHTML = '<span>' + max_user.nickname + '</span>';
				$('header').className = 'header logged';
				document.body['hideTarget'] = null;
				$('login-block').style['display'] = 'none';
				document.body.onclick = null;
			}
		}
	)
}
function doLogout() {
	window.location = '/logout';
}

/* show functions */
function showLogin(evt) {
	evt = evt || window.event;
	var root = $('login-block');
	root.style['display'] = 'block';
	document.body['hideTarget'] = root;
	document.body.onclick = $hide;
	if (window.event)
		evt.cancelBubble = true;
	else
		evt.stopPropagation();
}
function showUserInfo(evt) {
	evt = evt || window.event;
	var passport = $('passport');
	var opened = passport.className == 'passport opened';
	passport.className = opened ? 'passport' : 'passport opened';
	var root = $('userinfo-block');
	root['hideEvent'] = function () {passport.className = 'passport'};
	if (opened) {
		return;
	}
	else {
		var p = getLocation(passport);
		root.style['top'] = p.y - (-29) + 'px';
		root.style['left'] = p.x - (-1) + 'px';
		root.style['display'] = 'block';
		document.body['hideTarget'] = root;
		document.body.onclick = $hide;
		if (window.event)
			evt.cancelBubble = true;
		else
			evt.stopPropagation();
	}
}
function showSelect(evt, tar, data, direction) {
	evt = evt || window.event;
	var root = $('select-block');
	if (root.style['display'] == 'block') {
		return;
	}
	root.innerHTML = '';
	for (var i in data) {
		var temp = data[i];
		var item = document.createElement('a');
		root.appendChild(item);
		item.innerHTML = temp.title;
		item['offset'] = i;
		if (temp.func) item['func'] = temp.func;
		item.href = "#";
		item.onclick = function () {return false;}
	}
	root.onclick = function (evt) {
		evt = evt || window.event;
		var target = evt.target || evt.srcElement;
		while (target.tagName.toLowerCase() != 'a') {
			if (target == root) return;
			target = target.parentNode;
		}
		tar['current'] = target.offset;
		if (target.func) target.func();
		tar.innerHTML = target.innerHTML + '<img alt="" src="/images/icons/select.png" />';
		document.body['hideTarget'] = null;
		root.style['display'] = 'none';
		document.body.onclick = null;
	};
	var p = getLocation(tar);
	root.style['display'] = 'block';
	if (direction)
		root.style['top'] = p.y - root.offsetHeight + 'px';
	else
		root.style['top'] = p.y - (-29) + 'px';
	root.style['left'] = p.x - (-1) + 'px';
	document.body['hideTarget'] = root;
	document.body.onclick = $hide;
	if (window.event)
		evt.cancelBubble = true;
	else
		evt.stopPropagation();
}

/* hide function */
function $hide(evt) {
	evt = evt || window.event;
	var target = evt.target || evt.srcElement;
	var root = document.body['hideTarget'];
	if (!root) return;
	while (target.tagName.toLowerCase() != 'body') {
		if (target == root)
			return;
		target = target.parentNode;
	}
	document.body['hideTarget'] = null;
	root.style['display'] = 'none';
	if (root.hideEvent) {
		root.hideEvent();
		root.hideEvent = null;
	}
	document.body.onclick = null;
}

/* basic functions */
function getLocation(obj) {
	if (!obj)
		return;
	var left = obj.offsetLeft;
	var top = obj.offsetTop;
	var objParent = obj.offsetParent || obj.parentNode;
	while(objParent.className != "wrapper") {
		left += objParent.offsetLeft;
		top += objParent.offsetTop;
		objParent = objParent.offsetParent || objParent.parentNode;
	}
	return {'x': left, 'y': top};
}

function $(id) {return document.getElementById(id)}
function $encode(str) {return encodeURIComponent(str)}
function $decode(str) {return decodeURIComponent(str)}
function newRequest() {
	if (window.XMLHttpRequest) // Mozilla, Safari, ...
		return new XMLHttpRequest();
	else if (window.ActiveXObject) // IE
		return new ActiveXObject("Microsoft.XMLHTTP");
}
function getRequest(url, handler) {
	var request = newRequest();
	request.onreadystatechange = function() {handler(request)};
	request.open('GET', url, true);
	request.send(null);
}
function postRequest(url, params, handler) {
	var request = newRequest();
	request.onreadystatechange = function() {handler(request)};
	request.open('POST', url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(params);
}
function rand(){
	return Math.round(Math.random()*1000000);
}
function today(){
	var date = new Date();
	return String(date.getMonth() + 1) + '/' + String(date.getDate());
}
function loadScript(src, rid){
	document.write('<scr'+'ipt type="text/javascript" src="'+src.replace('{rid}', rid)+'"></scr'+'ipt>');
}

/* init */
function init() {
	if(max_user && max_user.nickname){
		$('username').innerHTML = '<span>' + max_user.nickname + '</span>';
		$('header').className = 'header logged';
	}
}

function switchBlock(self, id){
	var e = $(id);
	var s = e.style;
	var b = (s.display != 'none');
	s.display = b ? 'none' : 'block';
	if(self) self.src = b ? "/images/icons/expand.png":"/images/icons/collpse.png";
}

//http://addons.dev.maxthon.cn/zh_cn/post/1078
function generateList(list){
	var res = '<ul>';
	for(var i=0; i<list.length; i++){
		res += '<li><a href="/'+CURRENT_LANGUAGE+'/post/'+list[i].id+'">'+list[i].name+'</a></li>';
	}
	res += '</ul>';
	document.write(res);
}

function generateCategories(list){
	var res = '<ul class="categories">';
	for(var i=0; i<list.length; i++){
		if(list[i].parent_id==0){
			res += '<li><span class="title"><img alt="" src="/images/icons/'+list[i].name+'.png" /><a href="/'+CURRENT_LANGUAGE+'/category/'+list[i].name+'">'+list[i].fullname+'</a></span></li>';
			res += '<ul class="sub-category">';
			for(var j=0; j<list.length; j++){
				if(list[j].parent_id==list[i].id)
					res +=  '<li><a href="/'+CURRENT_LANGUAGE+'/category/'+list[j].name+'">'+list[j].fullname+'</a></li>';
			}
			res += '</ul>';
		}
	}
	res += '</ul>';
	document.write(res);
}