var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function scanTag(tag,tagName,att) {
	var output = new Array;
	if ( att == undefined ) att = 'id';
	if ( !( tagName instanceof Array ) ) tagName = new Array(tagName);

	if ( tag != undefined ) {	
		var children = tag.childNodes;
		for ( var i = 0; i < children.length; i++ ) {
			if ( children[i].childNodes != undefined ) {
				var a = scanTag( children[i], tagName, att );
				if ( a != null ) 
					if ( a.length > 0 ) output = output.concat(a);
			}
			
			if ( children[i].tagName != undefined ) {	
				for ( var j = 0; j < tagName.length; j++ ) {
					if ( children[i].tagName == tagName[j] ) {
						var id = children[i].getAttribute( ( att instanceof Array ) ? att[j] : att );
						if ( id != null ) 
							if ( id.length > 0 ) output.push(id);
					}
				}
			}
		}
	}
	
	return output;
}

function scanTagFormElements() {
	
}

function getElementsBySplittedList(tagList) {
	var t = tagList.split(',');
	var a = new Array;
	
	for ( var i = 0; i < t.length; i++ ) {
		a[i] = document.getElementById(t[i]);
	}
	
	return a;
}

var http_request = false;

function makeRequest(method, url, args, func) {

	if ( method == 'GET' ) {
		if ( args != "" ) {
			if ( url.indexOf('?') >= 0 ) 
				url = url + "&" + args;
			else
				url = url + "?" + args;
		}
	}
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
		
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {						
				var results = http_request.responseText;
				return func(results);
			} else if ( http_request.status == 404 ) {
				alert( "Request URL does not exist!\n"+url);
			} else {
				alert( "Error : status code is " + http_request.status + 
					   http_request.responseText.replace('<h1>','').replace('</h1>',''));
			}
		}
	};
	http_request.open(method, url, true);

	if ( method == 'POST' ) {
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", args.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(args);
	}
	else
		http_request.send(null);
}

function emptyValidation() {  /* Id_1, Id_2, Id_3, .... etc */
	
	var argv = emptyValidation.arguments;
	var argc = argv.length;
	var counter = 0;
	
	for (var i = 0; i < argc; i++) {
		if ( document.getElementById(argv[i]) ) {
			if ( document.getElementById(argv[i]).value.length == 0 || document.getElementById(argv[i]).value == null ) {
					document.getElementById(argv[i]).style.backgroundColor="#FF0000";
					counter++;
			} else {
				document.getElementById(argv[i]).style.backgroundColor="#FFFFFF";	
			}
		}
	}
	
	if(counter>0)
		return false;
	else
		return true;
}

function list_data(url, args, id) {
	
	var my_func = function ( results ) {
		document.getElementById(id).innerHTML = results;
	};
	
	if ( args.length > 0 && args != null ) args = "&"+args;
	args = "act=list" + args;
	
	makeRequest('GET', url, args, my_func);
}

function new_data(url, args, id) {
	var my_func = function ( results ) {
		document.getElementById(id).innerHTML = results;
	};
	
	if ( args.length > 0 && args != null ) args = "&"+args;
	args = "act=new" + args;
	
	makeRequest('GET', url, args, my_func);
}

function edit_data(url, args, id) {
	var my_func = function ( results ) {
		document.getElementById(id).innerHTML = results;
	};
	
	if ( args.length > 0 && args != null ) args = "&"+args;
	args = "act=edit" + args;
	
	makeRequest('GET', url, args, my_func);
}

function save_data(url, args, id) { /* url, args, field_1, field_2, field_3, .... etc */
	
	var argv = save_data.arguments;
	var argc = argv.length;
	 
	if ( argc > 3 ) {
		
		var s = "emptyValidation(";
	
		for (var i = 3; i < argc; i++) {
			if ( typeof document.getElementById( argv[i] ) == 'undefined' ) {
				alert ( 'Ajax field not found : ' + argv[i] );
				return;
			}
			if ( document.getElementById( argv[i] ).type == 'text' ) {
				s += ("'" + argv[i] + "'");
				s += (i+1 != argc )?',':'';
			}
		}
		s += ")";
						
		if ( eval(s) ) { /* call emptyValidation */
			if ( args.length != 0 && args != null && argc > 3 ) args += "&";
			args += "act=save&";
			for (var i = 3; i < argc; i++) {
				if ( document.getElementById( argv[i] ).type == "checkbox" )
					args += argv[i] + "=" + ((document.getElementById( argv[i] ).value=="on")?"TRUE":"FALSE");
				else
					args += argv[i] + "=" + Url.encode(document.getElementById( argv[i] ).value);
				if ( i+1 != argc ) args += "&";
			}
						
			var my_func = function ( results ) {
				document.getElementById(id).innerHTML = results;
			};
			
			makeRequest('GET', url, args, my_func);
		} 
	}
}

function del_data(url, args, id) {
	
	if ( confirm('你確定要刪除這個記錄？') ) {
	
		var my_func = function ( results ) {
			document.getElementById(id).innerHTML = results;
		};
		
		if ( args.length > 0 && args != null ) args = "&"+args;
		args = "act=del" + args;
		
		makeRequest('GET', url, args, my_func);
	}
}

function makeAction(url, args, id, act, func) {
	if ( typeof func == 'undefined' )
		var my_func = function ( results ) {
			document.getElementById(id).innerHTML = results;
		};
	else
		var my_func = func;
		
	if ( args.length > 0 && args != null ) args = "&"+args;
	args = "act=" + act + args;
	
	makeRequest('GET', url, args, my_func);
}

function asyncSubmit(url, args, id, func) {
	if ( typeof func == 'undefined' )
		var my_func = function ( results ) {
			document.getElementById(id).innerHTML = results;
		};
	else
		var my_func = func;
	
	var f = document.getElementById(id);
	var t = Array( 'INPUT', 'SELECT' );
	var a = scanTag(f, t);
		
	for ( var i = 0; i < a.length; i++ ) a[i] = document.getElementById(a[i]);
	
	if ( args.length > 0 && args != null ) args = "&"+args;
	args = "act=submit" + args + "&";
		
	for ( var i = 0; i < a.length; i++ ) {
		if ( a[i].type == 'checkbox' )
			args += ( a[i].id+'='+(a[i].checked?'TRUE':'FALSE') );
		else if ( typeof a[i].selectedIndex == 'number' ) 
			args += ( a[i].id+'='+Url.encode(a[i].options[a[i].selectedIndex].value) );
		else
			args += ( a[i].id+'='+Url.encode(a[i].value) );
		if ( i+1 != a.length ) args += "&";
	}
	
	makeRequest('POST', url, args, my_func);
}

function Loading(id, url, text) {
	var d = document.getElementById(id);
	var html = "";
	
	html = "<img src=\"" + url + "\" alt=\"Loading\">&nbsp;&nbsp;&nbsp;&nbsp;";
	if ( typeof text == 'undefined' ) text = "Loading...";
	html = html + text;
	
	d.innerHTML = html;
}

