AJL = {}

AJL.HTTP = {
    encode: function(obj) {
        var ary = [];
        for (var name in obj) {
            var value = obj[name];
            if (value instanceof Array)
                for (var i = 0; i < value.length; ++i)
                    ary.push(encodeURIComponent(name) + '=' +
                             encodeURIComponent(value[i]));
            else
                ary.push(encodeURIComponent(name) + '=' +
                         encodeURIComponent(value));
        }
        return ary.join(AJL.HTTP.encode.separator);
    },
    Client: function(config) {
        this.header = {};
        if (!config)
            config = {};
        this.receiver = config.receiver;
        this.username = config.username;
        this.password = config.password;
        this.onrequest = null;
        this.onresponse = null;
    },
    Thread: function(xmlhttp) {
        this.xmlhttp = xmlhttp;
    }
}

AJL.HTTP.encode.separator = '&';

AJL.HTTP.Client.prototype = {
    get: function(path, query, handler) {
        path = this.joinPathAndQuery(path, query);
        return this.sendRequest('GET', path, null, handler);
    },
    post: function(path, body, handler) {
        if (body.toString == Object.prototype.toString)
            body = AJL.HTTP.encode(body);
        return this.sendRequest('POST', path, body, handler);
    },
    head: function(path, query, handler) {
        path = this.joinPathAndQuery(path, query);
        return this.sendRequest('HEAD', path, null, handler);
    },
    joinPathAndQuery: function(path, query) {
        if (query != null) {
            if (query.toString == Object.prototype.toString)
                query = AJL.HTTP.encode(query);
            path += '?' + query;
        }
        return path;
    },
    sendRequest: function(method, path, body, handler) {
        var xmlhttp = window.XMLHttpRequest ?
            new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
        var async = handler != undefined;
        xmlhttp.open(method, path, async, this.username, this.password);
        for (var name in this.header)
            xmlhttp.setRequestHeader(name, this.header[name]);
        if (method == 'POST' && 'Content-Type' in this.header == false)
            xmlhttp.setRequestHeader('Content-Type',
                                     'application/x-www-form-urlencoded');
        if (this.mimetype && xmlhttp.overrideMimeType)
            xmlhttp.overrideMimeType(this.mimetype);
        if (this.onrequest != null)
            try {
                this.onrequest.call(this.receiver);
            } catch (e) {}
        if (async) {
            var thread = new AJL.HTTP.Thread(xmlhttp);
            xmlhttp.onreadystatechange =
                this.createResponseHandler(xmlhttp, handler, this, thread);
            xmlhttp.send(body);
            return thread;
        } else {
            xmlhttp.send(body);
            if (this.onresponse != null)
                try {
                    this.onresponse.call(this.receiver);
                } catch (e) {}
            var response = this.createResponseObject(xmlhttp);
            if (response instanceof Error)
                throw response;
            return response;
        }
    },
    createResponseHandler: function(xmlhttp, handler, client, thread) {
        return function() {
            if (xmlhttp.readyState == 4) {
                if (client.onresponse != null)
                    try {
                        client.onresponse.call(client.receiver);
                    } catch (e) {}
                var response = client.createResponseObject(xmlhttp);
                thread.result = handler.call(client.receiver, response);
                if (AJL.debug && response instanceof Error)
                    throw response;
            }
        };
    },
    createResponseObject: function(xmlhttp) {
        try {
            if (/^\d{3}$/.test(xmlhttp.status) ||
                location.protocol == 'file:') {
                var obj = {text: xmlhttp.responseText, status: xmlhttp.status,
                           reason: xmlhttp.statusText, header: {}};
                if (xmlhttp.responseXML &&
                    xmlhttp.responseXML.documentElement)
                    obj.xml = xmlhttp.responseXML.documentElement;
                if (xmlhttp.getAllResponseHeaders()) {
                    var ary = xmlhttp.getAllResponseHeaders().split('\n');
                    for (var i = 0; i < ary.length; ++i)
                        if (ary[i].match(/^(.*?): (.*?)\r?$/))
                            obj.header[RegExp.$1] = RegExp.$2;
                }
                return obj;
            }
        } catch (e) {}
        return AJL.createError('no response from server');
    }
}

AJL.HTTP.Thread.prototype = {
    abort: function() {
        if (this.xmlhttp.readyState != 4) {
            this.xmlhttp.onreadystatechange = function() {};
            this.xmlhttp.abort();
        }
    }
}

AJL.Loader = function(client) {
    this.client = client || new AJL.HTTP.Client;
    this.client.mimetype = 'text/xml';
    this.setRandomNumberToQuery = false;
};

AJL.Loader.prototype = {
    loadtext: function(path, handler) {
        return this.load(path, handler, this.extractText);
    },
    loadxml: function(path, handler) {
        return this.load(path, handler, this.extractRootElement);
    },
    load: function(path, handler, extract) {
        if (this.setRandomNumberToQuery && path.indexOf('?') == -1)
            path += '?' + String(Math.random()).substring(2);
        if (handler == null) {
            var result = extract(this.client.get(path));
            if (result instanceof Error)
                throw result;
            return result;
        } else
            return this.client.get(path, null,
                                   this.wrapHandler(handler,
                                                    this.client.receiver,
                                                    extract));
    },
    wrapHandler: function(handler, receiver, extract) {
        return function(response) {
            var obj = extract(response);
            var result = handler.call(receiver, obj);
            if (AJL.debug && obj instanceof Error)
                throw obj;
            return result;
        };
    },
    extractText: function(response) {
        if (response instanceof Error)
            return response;
        if (response.status == 200 || response.status == 304 ||
            response.status == 0 || response.status == null)
            return response.text;
        else
            return AJL.createError(response.reason);
    },
    extractRootElement: function(response) {
        if (response instanceof Error)
            return response;
        if (response.status != 200 && response.status != 304 &&
            response.status != 0 && response.status != null)
            return AJL.createError(response.reason);
        if (response.xml)
            return response.xml;
        var xmldoc = document.implementation.createDocument ?
            document.implementation.createDocument('', '', null) :
            new ActiveXObject('Microsoft.XMLDOM');
        if (typeof xmldoc.loadXML != 'undefined')
            xmldoc.loadXML(response.text.replace(/^<\?xml.*?\?>/, ''));
        return xmldoc.documentElement ||
            AJL.createError('can not build xml dom tree');
    }
};

//Encode
AJL.encodeSTR = function(str) {
	var moji;
	var uni = "";
	for( var i=0;i<str.length;i++){
		moji = str.charCodeAt(i);
		if(moji <= 255){
			if(moji <=15){
				uni = uni + "%0" + moji.toString(16);
			} else if(moji >=48 && moji <=57){
				uni = uni + str.charAt(i);
			} else if(moji >=65 && moji <=90){
				uni = uni + str.charAt(i);
			} else if(moji >=97 && moji <=122){
				uni = uni + str.charAt(i);
			} else {
				uni = uni + "%" + moji.toString(16);
			}
		} else {
			uni = uni + "%u" + moji.toString(16);
		}
	}
	return uni;
}

//Decode
AJL.decodeSTR = function(s){
	var seq = "";
	var abc = "";
	var uni = "";
	
   str1 = "012345";
    str2 = str1.charAt(2);      // "2"
    str3 = str1.substring(2,4); // "23"
    
    for (var i = 0; i < s.length;) {
    	var c = s.charAt(i);
    	if (c == '%') {
    		if (s.charAt(i+1) == 'u') {
				uni = s.substr(i+2,4);
				seq += String.fromCharCode(parseInt(uni,16));
				i += 6;
    		} else {
				abc = s.substr(i+1,2);
    			seq += String.fromCharCode(parseInt(abc,16));
    			i+=3;
    		}
    	} else {
    		seq += c;
    		i++;
    	}
    }
	return seq;
}

AJL.getClientSize = function()
{
	var w = document.documentElement.clientWidth;
	var h = document.documentElement.clientHeight;
	
	if (w == 0) {
		w = document.body.clientWidth;
	}
	if (h == 0) {
		h = document.body.clientHeight;
	}
	var ret = {cx: w, cy: h};
	return ret;
};

//ƒoƒCƒ“ƒh
function bind(method, receiver) {
    return function() {
        return method.apply(receiver, arguments);
    };
}

