var myAjaxObjects = new Array();
var myAjaxIndex = 1;

function ajax(url, params, index, onLoad){
	var ajaxIndex = (index == 0) ? myAjaxIndex++ : index;
	myAjaxObjects[ajaxIndex] = new sack();
	myAjaxObjects[ajaxIndex].requestFile = url;
	if(params != null){
		for (var i in params) {
			if(typeof(params[i]) == "object"){
				var tmp = ajax_obj2str2(params[i]);
				myAjaxObjects[ajaxIndex].setVar(i, tmp);
			}else{
				myAjaxObjects[ajaxIndex].setVar(i, params[i]);
			}
		}
	}
	myAjaxObjects[ajaxIndex].onCompletion = function(){ajax_loaded(url, params, ajaxIndex, onLoad);};	
	myAjaxObjects[ajaxIndex].runAJAX();
}
function ajax_loaded(url, params, ajaxIndex, onLoad){
	var result = myAjaxObjects[ajaxIndex].response;
	if(result != ""){
		var responseObj = ajax_responseParse(result);
		if(typeof(responseObj) != "object") alert(result);

		if(responseObj["include_css"]){
			if(responseObj["include_css"] != "") loadCSS(responseObj["include_css"]);
		}
		if(responseObj["include_js"]){
			if(responseObj["include_js"] != "") loadJS(responseObj["include_js"]);
		}
		if(responseObj.response.confirm){
			confirm = responseObj.response.confirm;
			var onConfirm = function(e){
				window[confirm.action](confirm.param);
			}
			new myConfirm(confirm.text, onConfirm);
		}
		if(responseObj.response.msgbox){
			msgbox = responseObj.response.msgbox;
			//alert(msgbox.text+": "+msgbox.action+": "+msgbox.param);
			var onConfirm = function(e){
				window[msgbox.action](msgbox.param);
			}
			new myMsgbox({msg:msgbox.text});
		}
		if(responseObj.response.redirect){
			url = responseObj.response.redirect;
			location.href = url;
		}
		if(responseObj.response.eval){
			var tmp = String(responseObj.response.eval);
			eval(tmp);
		}
		if(responseObj.response.debug) alert(responseObj.response.debug);
		if(responseObj.response){
			onLoad(responseObj);
		}
		if(responseObj.response.onload){
			onload = responseObj.response.onload;
			//alert(onload.action+":"+onload.param);
			window[onload.action](onload.param);
		}
	}else{

	}
}
function ajax_load(url,elemid){
	myAjaxIndex++;
	ajaxIndex = myAjaxIndex;

	var onCompletion = function(){
		var result = myAjaxObjects[ajaxIndex].response;
		var elem = getElem(elemid);
		elem.innerHTML = utf8.decode(result);
	}

	myAjaxObjects[ajaxIndex] = new sack();
	myAjaxObjects[ajaxIndex].requestFile = url;
	myAjaxObjects[ajaxIndex].onCompletion = onCompletion;
	myAjaxObjects[ajaxIndex].runAJAX();
}
function ajax_responseParse(response){
	if(response.substring(0,1) == "{"){
		eval('var obj = '+response);
		var response = ajax_responseReplaceQuot(obj);
	}
	return response;
}
function ajax_responseReplaceQuot(obj){
	for (var i in obj){
		if(typeof(obj[i]) == "object"){
			ajax_responseReplaceQuot(obj[i]);
		}else{
			if(typeof(obj[i]) == "string"){
				var str = obj[i];
				str = str.replaceAll("[#crlf]", "\n");
				str = str.replaceAll("[#quot]", "\"");
				str = str.replaceAll("[#comma]", ",");
				str = str.replaceAll("[#colon]", ":");
				str = str.replaceAll("[#squot]", "'");
				obj[i] = str;
			}
		}
	}
	return obj;
}
function serialize (mixed_value) {
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/serialize    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];                    break;
                }
            }
        }
        return type;    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
			//mixed_value = utf8.encode(mixed_value);
            //val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
			val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }            */
            var count = 0;
            var vals = "";
            var okey;
            var key;            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";    }
    return val;
}
function serialize1(_obj)
{
   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
   {
      return _obj.toSource();
   }

   // Other browsers must do it the hard way
   switch (typeof _obj)
   {
      // numbers, booleans, and functions are trivial:
      // just return the object itself since its default .toString()
      // gives us exactly what we want
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;

      // for JSON format, strings need to be wrapped in quotes
      case 'string':
         return '\'' + _obj + '\'';
         break;

      case 'object':
         var str;
         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined')
         {
            str = '[';
            var i, len = _obj.length;
            for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
            str += serialize(_obj[i]) + ']';
         }
         else
         {
            str = '{';
            var key;
            for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
            str = str.replace(/\,$/, '') + '}';
         }
         return str;
         break;

      default:
         return 'UNKNOWN';
         break;
   }
}

function ajax_obj2str(obj){
	var result = "";
	if(typeof(obj) == "object"){
		for (var i in obj) {
			if(typeof(obj[i]) == "object"){
				result += ajax_obj2str(obj[i]);
			}else{
				result += i+"="+obj[i] + "\n"
			}
		}
	}
	return result;
}

function ajax_obj2str2(obj){
	var result = "";
	if(typeof(obj) == "object"){
		var c = 0;
		for (var i in obj) {
			if(typeof(obj[i]) == "object"){
				result += ajax_obj2str2(obj[i]);
			}else{
				tmp = obj[i];
				if(typeof(obj[i]) == "string"){
				tmp = tmp.replaceAll(",", "[#comma]");
				tmp = tmp.replaceAll(":", "[#colon]");
				tmp = tmp.replaceAll("\"", "[#quot]");
				tmp = tmp.replaceAll("'", "[#squot]");
				}
				result += i+":"+tmp+",";
			}
		}
	}
	result = result.trim(",");
	return "{"+result+"}";
}

function ajax_save(table, identity, id, name, elem){
	//alert("table: "+table+", id: "+id);
	elem = getElem(elem);
	if(elem.checked){
		value = elem.value
	}else{
		value = "";
	}
	var f = function(arg){ void(0); }
	ajax("ajax_db.php", {table:table, identity:identity, id:id, name:name, value:value}, 0, f);
}
