var EscapeHtml = {
    LT:new RegExp("<", "g"),
    GT:new RegExp(">", "g"),
    AMP:new RegExp("&", "g"),
    TAB:new RegExp("\t", "g"),
    escape:function(s) {
        return s.replace(this.AMP,"&amp;").replace(this.LT, "&lt;").replace(this.GT, "&gt;").replace(this.TAB, "    ");
    }
}
function ScrollAjax(scroll, config) {
    this.scroll = scroll;
    this.config = config?config:{};

    /*
                scroll.appendHeader(">> "+value);
                if (value=="cls") {
                    scroll.clear();
                    scroll.createPrompt(">> ");
                } else if (value=="adios") {
                    scroll.removePrompt();
                } else {
                    scroll.appendText("Tralari tralara...");
                    scroll.createPrompt(">> ");
                }
    */

    this.submit = function(scroll) {
        var phrase = scroll.getPromptContent().clean();

        if (this.config.onSubmit) {
            var result = this.config.onSubmit(phrase);
            if (result == false) {
                return;
            } else if (result != null) {
                phrase = result;
            }
        }

        if (phrase == ':cls') {
            scroll.clear();
            scroll.createPrompt();
            return false;
        }
        if (phrase == '') {
            scroll.createPrompt();
            scroll.scrollToBottom();
            scroll.focus();
            return false;
        }

        if (!scroll.fixedPrompt) {
            scroll.removePrompt();
        }
        scroll.appendHeader(scroll.defaultPrompt + EscapeHtml.escape(phrase));

        this.sendPhrase(phrase, false);
        return false;
    }

/*
    this.autoSendPhrase = function(phrase, refresh) {
        alert('a')
        scroll.ensurePrompt();
        scroll.getPromptField().value = phrase;
        scroll.submit();
    }
*/

    this.sendPhrase = function(phrase, refresh) {
        var params = Object.toQueryString({
            phrase: phrase,
            from: scroll.id,
            refresh: refresh,
            logDebug : sLogDebug,
            logParsing: sLogParsing,
            anticache : new Date().getTime()});

        this.send("do", "post", params, phrase);

    }

    this.saveSource = function(part, data) {
        var params = Object.toQueryString({
            from: scroll.id,
            logDebug : sLogDebug,
            part: part,
            data: data,
            logParsing: sLogParsing,
            anticache : new Date().getTime()});
        this.send("put", "post", params, data);

    }

    this.send = function(url, method, params, data) {
        if (this.config.onSend && this.config.onSend(data) == false) {
            return;
        }

        new Ajax(url, {
            method: method,
            data: params,
            evalScripts: true,
            onComplete: this.completed.bind(this)
            }).request();
    }

    this.completed = function(text, xml) {
//        try {
            // Eliminamos los scripts
            text = text.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, '');

            if (this.config.onComplete && this.config.onComplete(text) == false) {
                return;
            }

            var o = {fields:[], values:[], methods:[], params:[]};
            eval("o = "+text);
            if (o.fields && o.values && o.methods ) {
                for (var i = 0; i < o.fields.length; i++) {
                    var fieldId = o.fields[i];
                    var value = o.values[i];
                    var method = o.methods[i];
                    var params = o.params[i];
//                    alert("Campo '"+fieldId+"', metodo '"+method+"' longitud valor: "+value.length+" params "+params);
                    var field = $(fieldId);

                    if (this.config.onField && this.config.onField(fieldId, value, method, params) == false) {
                        continue;
                    }

                    if (method == "replace" || method == "append") {
                        if (!this.config.onFieldReplace || this.config.onFieldReplace(field, value, method, params) != false) {
                            // Si no existe la funcion o existe pero no retorna false, modificamos el campo
                            if (field) {
//                                if (debugScroll && sLogDebug) {
//                                    debugScroll.append("* Campo recibido ["+fieldId+"]: "+value);
//                                }
                                field.setText(value);
                            } else {
//                                if (debugScroll && sLogDebug) {
//                                    debugScroll.append("* Campo no existe ["+fieldId+"]: "+value);
//                                }
                            }
                        }
                    } else if (method == "scroll" || method == "scrollinput") {
                        var scrollDest = ScrollableDiv.get(fieldId);
                        if (scrollDest == null) {
                            continue;
                        }
                        if (value.length > 0 && value != "-") {
                            scrollDest.removePrompt();
                            if (!this.config.onFieldScroll || this.config.onFieldScroll(scrollDest, value, method, params) != false) {
                                // Si no existe la funcion o existe pero no retorna false, modificamos el campo
                                scrollDest.appendText(value);
                            }
                            scrollDest.scrollToBottom();
                        }
                        if (method == "scrollinput" && scrollDest.prompt) {
                            scrollDest.ensurePrompt();
                        }
    //                } else {
    //                    alert("Metodo '"+method+"' desconocido en campo '"+fieldId+"'");
                    }
                }
    //        } else {
    //            alert("ops, falta algo...")
            }


            if (this.config.onFinish && this.config.onFinish(text) == false) {
                return;
            }

//        } catch (e) {
//            alert("onCompleted exception: "+e);
//        }



    }
}